package com.ocom.payhandle.fun.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.HttpUtils;
import com.ocom.common.entity.card.*;
import com.ocom.common.entity.company.EntityCompanyConfig;
import com.ocom.common.entity.pay.EntityXfRecordProcessExtend;
import com.ocom.common.entity.payconfig.EntityXfDeviceMealConfig;
import com.ocom.common.entity.typehandler.EntityCcbPosInfo;
import com.ocom.common.entity.typehandler.SignNoHandle;
import com.ocom.common.enums.OpTypeDiffEnum;
import com.ocom.common.enums.PayWar;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.payconfig.mealorder.RefundOrderDishesRequest;
import com.ocom.common.request.payhandle.GzhRechageRefundRequest;
import com.ocom.common.request.payhandle.QrCardPayRequest;
import com.ocom.common.request.payhandle.QrCodeQueryRequest;
import com.ocom.common.request.payhandle.QrCodeRefundRequest;
import com.ocom.common.request.simple.SmsRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.*;
import com.ocom.common.vo.devicehttp.MachMealDataVo;
import com.ocom.common.vo.pyhandle.AnalyzeBankUsersVo;
import com.ocom.common.vo.pyhandle.ConsTimeZoneVo;
import com.ocom.common.vo.pyhandle.FeePlanVo;
import com.ocom.common.vo.pyhandle.VoucherListVo;
import com.ocom.payhandle.feign.MqSimpleFeign;
import com.ocom.payhandle.feign.PayConfigClientService;
import com.ocom.payhandle.feign.XfRecordFeign;
import com.ocom.payhandle.fun.PayFunService;
import com.ocom.payhandle.fun.PayHandleFunService;
import com.ocom.payhandle.mq.business.saveorder.SaveOrderProductService;
import com.ocom.payhandle.service.*;
import com.ocom.payhandle.vo.MqSaveOrderVo;
import com.ocom.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Slf4j
@Service
public class PayFunServiceImpl implements PayFunService {

//    @Value("${pay.url}")
//    private String payUrl;

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private XfRecordProcessExtendService xfRecordProcessExtendService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private XfRecordFeign xfRecordFeign;

    @Autowired
    PayHandleFunService payHandleFunService;

    @Autowired
    PersonnelInfoService personnelInfoService;

    @Autowired
    CcbPosInfoService ccbPosInfoService;

    @Autowired
    XfChannelInfoService xfChannelInfoService;

    @Autowired
    private XfRecordProcessService xfRecordProcessService;

    @Autowired
    private XfSignNoService xfSignNoService;

    @Autowired
    private VoucherDataService voucherDataService;

    @Autowired
    private XfZoneDateService xfZoneDateService;

    @Autowired
    private SaveOrderProductService saveOrderProductService;

    @Autowired
    private XfGoodsListProcessService xfGoodsListProcessService;

    @Autowired
    private	XfMerchantInfoService xfMerchantInfoService;

    @Autowired
    private XfCardInfoService xfCardInfoService;

    @Autowired
    private XfAccountTypeService xfAccountTypeService;

    @Autowired
    XfRepairpayConfigService xfRepairpayConfigService;

    @Autowired
    XfRecordWaitpayService xfRecordWaitpayService;

    @Autowired
    private XfAccountInfoService xfAccountInfoService;

    @Autowired
    private CompanyConfigService companyConfigService;

    @Autowired
    private XfSignOrderService xfSignOrderService;

    @Autowired
    private XfMerchPayInfoService xfMerchPayInfoService;

    @Autowired
    PayConfigClientService payConfigClientService;

    @Autowired
    private MqSimpleFeign mqSimpleFeign;

    @Autowired
    XfUserparamConfigService xfUserparamConfigService;

    @Override
    public Long AnalyzeBankUsers(AnalyzeBankUsersVo analyzeBankUsersVo) {
        analyzeBankUsersVo.setMerchId(0);
        EntityXfRecordProcess entityXfRecordProcess = new EntityXfRecordProcess();
        entityXfRecordProcess.setOrderNo("");
        entityXfRecordProcess.setComId(analyzeBankUsersVo.getCompanyId());
        entityXfRecordProcess.setMerchId(analyzeBankUsersVo.getMerchId().longValue());
        EntiyXfMerchPayInfo entiyXfMerchPayInfo = payHandleFunService.configure(entityXfRecordProcess);

        Map<String, Object> retMap = new HashMap<>();

        //向统一支付平台发起支付
        retMap.put("companyId", entiyXfMerchPayInfo.getCompanyId());
        retMap.put("userName", entiyXfMerchPayInfo.getUserName());
        retMap.put("payPassword", entiyXfMerchPayInfo.getPassword());
        retMap.put("qrCode", analyzeBankUsersVo.getAuthCode());
        String payUrl = companyInfoService.getPayCenterUrl(analyzeBankUsersVo.getCompanyId(), entiyXfMerchPayInfo.getCompanyId());
        String json = HttpUtils.postJson(payUrl + "/ccb/pay/analyzeCode.do", retMap);

        JSONObject results = JSON.parseObject(json);

        if (results.getInteger("code") == 200) {
            JSONArray jsonArray = (JSONArray) results.get("data");
            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
            String custId = jsonObject.getString("CUST_ID");

//            EntityPersonnelInfo entityPersonnelInfo = personnelInfoService.getPersonByPCode(analyzeBankUsersVo.getCompanyId(), custId);
//            if (entityPersonnelInfo == null) {
//                return 0l;
//            }
//            return entityPersonnelInfo.getPId();
            EntityXfSignNo entityXfSignNo = xfSignNoService.getUserSignInfo(analyzeBankUsersVo.getCompanyId(), 32, custId);
            if (entityXfSignNo == null) {
                return 0l;
            }
            return entityXfSignNo.getPId();
        }
        return 0l;
    }

    @Override
    public Integer CCBWithhold(EntityXfRecordProcess entityXfRecordProcess, QrCardPayRequest request,
                               EntityCardInfo entityCardInfo, JSONObject jsonObject, EntityXfSignNo xfSignNo) {

        entityXfRecordProcess.setOpTypeDiff(310L);
        entityXfRecordProcess.setPayWay(32);

        if (request.getType() == 1) {
            entityXfRecordProcess.setOpType(1l);
        } else if (request.getType() == 4) {
            entityXfRecordProcess.setOpType(22l);
        } else if (request.getType() == 7) {
            entityXfRecordProcess.setOpType(21l);
        } else if (request.getType() == 21 || request.getType() == 22) {
            entityXfRecordProcess.setOpType(2l);
        }


        String canKey = "ccb_pos_info#comId:" + entityXfRecordProcess.getComId() + "#deviceNo:" + request.getMachNo() + "#";
        Long timeLong = Long.valueOf(4 * 60 * 60);
        Object posObject = redisUtil.get(canKey);
        EntityCcbPosInfo entityCcbPosInfo = null;
        if (posObject == null) {
            entityCcbPosInfo = ccbPosInfoService.getDeviceInfo(entityXfRecordProcess.getComId(), request.getMachNo());
            if (entityCcbPosInfo == null) {
                log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "建行生活支付请求（强在线,代扣）", request.getMachNo(), request, "机器未绑定好柜台号和商家号");
                return 2;
            }
            redisUtil.set(canKey, entityCcbPosInfo, timeLong);
        } else {
            entityCcbPosInfo = (EntityCcbPosInfo) posObject;
        }

        try {
            int i = xfRecordProcessService.insertEntityXfRecord(request.getCompanyId(), entityXfRecordProcess);
            if (i <= 0) {
                log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "建行生活支付请求（强在线,代扣）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return -11;
            }
        } catch (Exception e) {
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式:【{}】,机器号:【{}】,入库新增等待表的数据:【{}】,异常的返回:【{}】,行号:【{}】", "建行生活支付请求（强在线,代扣）", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
            log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "建行生活支付请求（强在线,代扣）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
            //订单号重复
            return -11;
        }

        try {
            //查询配置信息
            EntiyXfMerchPayInfo entiyXfMerchPayInfo = payHandleFunService.configure(entityXfRecordProcess);
            if (entiyXfMerchPayInfo == null) {
                //商户支付渠道未配置"
                return -1;
            }


            JSONObject results = null;
            String json = "";

            SignNoHandle signNoHandle = new SignNoHandle();
            String custId = signNoHandle.decrypt(xfSignNo.getSignNo(), entityXfRecordProcess.getComId());

            Map<String, Object> retMap = new HashMap<>();
            retMap.put("companyId", entiyXfMerchPayInfo.getCompanyId());
            retMap.put("userName", entiyXfMerchPayInfo.getUserName());
            retMap.put("payPassword", entiyXfMerchPayInfo.getPassword());
            retMap.put("orderId", entityXfRecordProcess.getOrderNo());
            retMap.put("custId", custId);
            retMap.put("offline", 0);
            retMap.put("signTime", "");
            if (request.getType() == 22) {
                retMap.put("offline", 1);
                retMap.put("signTime", DateUtil.getStrDate(entityXfRecordProcess.getConsTime(),"yyyyMMddHHmmss"));
            }
            retMap.put("payment", Math.abs(entityXfRecordProcess.getPayAmount()));
            retMap.put("actualPayment", Math.abs(entityXfRecordProcess.getRealMoney()));
            retMap.put("businessId", entityCcbPosInfo.getBusinessId());
            retMap.put("vposId", entityCcbPosInfo.getVposId());
            retMap.put("couponInfo", "");
            if (CommonUtil.isNull(entityXfRecordProcess.getReserved1())) {
                retMap.put("couponInfo", entityXfRecordProcess.getReserved1());
            }
            retMap.put("accNos", "");

            String payUrl = companyInfoService.getPayCenterUrl(entityXfRecordProcess.getComId(), entiyXfMerchPayInfo.getCompanyId());

            if (request.getType() == 1 || request.getType() == 4 || request.getType() == 7) {

                retMap.put("cardId", entityXfRecordProcess.getAccountNo());

                //向统一支付平台发起支付
                json = HttpUtils.postJson(payUrl + "/ccb/pay/codePayment.do", retMap);
                results = JSON.parseObject(json);
            } else if (request.getType() == 21 ||  request.getType() == 22) {

                retMap.put("qrCode", request.getAuthCode());
                if (request.getType() == 22) {
                    retMap.put("qrCode", request.getFaceToken());
                }
                //向统一支付平台发起支付
                json = HttpUtils.postJson(payUrl + "/ccb/pay/scanCodePayment.do", retMap);
                results = JSON.parseObject(json);
            }

            if (results == null) {
                //支付结果未知
                return 0;
            }

            EntityXfRecordProcess updateXfRecordProcess = new EntityXfRecordProcess();
            updateXfRecordProcess.setId(entityXfRecordProcess.getId());
            updateXfRecordProcess.setPayChannelNo(entiyXfMerchPayInfo.getCompanyId());
            updateXfRecordProcess.setComId(entityXfRecordProcess.getComId());
            if (results.getInteger("code") == 200) {
                //支付成功，修改等待表的状态和把数据入成功表
                JSONArray jsonArray = (JSONArray) results.get("data");
                JSONObject jsonObjectR = (JSONObject) jsonArray.get(0);
                updateXfRecordProcess.setChannelOrderNo(jsonObjectR.getString("ACC_NO"));
                updateXfRecordProcess.setPayTime(new Date());
                updateXfRecordProcess.setPayState(1);
                try {
                    int i = xfRecordProcessService.updateEntityXfRecord(updateXfRecordProcess.getComId(), updateXfRecordProcess);
                    if (i <= 0) {
                        log.info("请求方式:【{}】,机器号:【{}】,入库修改的数据:【{}】,返回:【{}】", "建行生活支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), updateXfRecordProcess, "等待表修改入库失败");
                        log.info("请求方式:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "建行生活支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), retMap, json);
                    }
                } catch (Exception e) {
                    StackTraceElement ste = e.getStackTrace()[0];
                    log.info("请求方式:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】", "建行生活支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), updateXfRecordProcess, e, ste.getLineNumber());
                    log.info("请求方式:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "建行生活支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), retMap, json);
                }


                try {

                    entityXfRecordProcess.setPayTime(updateXfRecordProcess.getPayTime());
                    entityXfRecordProcess.setChannelOrderNo(updateXfRecordProcess.getChannelOrderNo());
                    entityXfRecordProcess.setPayWay(32);
                    entityXfRecordProcess.setPayState(1);
                    entityXfRecordProcess.setPayChannelNo(updateXfRecordProcess.getPayChannelNo());

                    String redOrdKey = "redisOrder:" + entityXfRecordProcess.getComId()+":"
                            +entityXfRecordProcess.getOrderNo();

                    String toJson = JsonUtils.toJson(entityXfRecordProcess);
                    redisUtil.set(redOrdKey,toJson,500l);

                    MqSaveOrderVo mqSaveOrderVo = new MqSaveOrderVo();
                    mqSaveOrderVo.setComId(entityXfRecordProcess.getComId());
                    mqSaveOrderVo.setId(entityXfRecordProcess.getId());
                    mqSaveOrderVo.setMachNo(entityXfRecordProcess.getDeviceNo());
                    mqSaveOrderVo.setRedisOrderNo(redOrdKey);
                    saveOrderProductService.saveOrder(mqSaveOrderVo);
                } catch (Exception e) {
                    StackTraceElement ste = e.getStackTrace()[0];
                    log.info("请求方式:【{}】,机器号:【{}】定时任务-入库成功表数据的数据:【{}】,异常的返回:【{}】,行号:【{}】", "建行生活支付请求（定时任务处理）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, e, ste.getLineNumber());
                }
                return 1;
            } else if (results.getInteger("code") == 16 || results.getInteger("code") == 19) {
                //支付结果未知
                return 0;
            } else {
                updateXfRecordProcess.setPayState(2);

                if(results.getString("msg")!=null){
                    if(results.getString("msg").length()>49) results.put("msg",results.getString("msg").substring(0,45));
                    updateXfRecordProcess.setReserved2(results.getString("msg"));
                }

                try {
                    int i = xfRecordProcessService.updateEntityXfRecord(entityXfRecordProcess.getComId(), updateXfRecordProcess);
                    if (i <= 0) {
                        log.info("请求方式:【{}】,机器号:【{}】,入库修改的数据:【{}】,返回:【{}】", "建行生活支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), updateXfRecordProcess, "等待表修改入库失败");
                        log.info("请求方式:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "建行生活支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), retMap, json);

                    }
                } catch (Exception e) {
                    StackTraceElement ste = e.getStackTrace()[0];
                    log.info("请求方式:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】", "建行生活支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), updateXfRecordProcess, e, ste.getLineNumber());
                    log.info("请求方式:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "建行生活支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), retMap, json);
                }
                log.info("请求方式:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "建行生活支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), retMap, json);
                jsonObject.put("msg", results.get("msg"));
                return 2;
            }
        } catch (Exception e) {
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式:【{}】,机器号:【{}】,入库新增等待表的数据:【{}】,异常的返回:【{}】,行号:【{}】", "建行生活支付请求（强在线）", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
            log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "建行生活支付请求（强在线）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
            //订单号重复
            return -11;
        }
    }

    @Override
    public Result qrCodeQuery(QrCodeQueryRequest request) {
        String machno = "";
        String tradeNo = "";
        try {
            machno = request.getMachNo();
            Long companyID = request.getCompanyId();
            tradeNo = request.getTradeNo();
            //查看数据库次订单是否支付成功
            EntityXfRecordProcess entityXfRecordProcess = xfRecordProcessService.selectTradeNo(companyID, tradeNo, request.getMachNo());
            if (entityXfRecordProcess == null) {
                //订单号号不存在
                return ResultUtil.error(ResultEnum.Err_805);
            }

            if(entityXfRecordProcess.getOpTypeDiff()>200l && entityXfRecordProcess.getDiscount()!=null && entityXfRecordProcess.getDiscount()>0){
                EntityXfRecordProcessExtend entityXfRecordProcessExtend = xfRecordProcessExtendService.getExtendInfo(companyID,entityXfRecordProcess.getId());
                if(entityXfRecordProcessExtend!=null && entityXfRecordProcessExtend.getCancelState()>0){
                    return ResultUtil.info(3030,"支付失败，优惠订单转入撤单");
                }
            }

			 //补缴单
            if(!CommonUtil.isNull(entityXfRecordProcess.getPlatOrderNo()) && !CommonUtil.isNull(entityXfRecordProcess.getOrigOrderNo())){
                //补缴单查询返回成功
                Map<String, Object> map = new HashMap<>();
                map.put("discount", entityXfRecordProcess.getDiscount());
                map.put("payAmount", entityXfRecordProcess.getRealMoney());
                map.put("pickupNum", entityXfRecordProcess.getReceiptNo());
                map.put("orderTime", DateUtil.getDateTime(entityXfRecordProcess.getPayTime()));
                return ResultUtil.success(map);
            }


            //获取订单号
            tradeNo = entityXfRecordProcess.getOrderNo();
            if (entityXfRecordProcess.getPayState() == 1) {
                //支付成功
                Map<String, Object> map = new HashMap<>();
                map.put("discount", entityXfRecordProcess.getDiscount());
                map.put("payAmount", entityXfRecordProcess.getRealMoney());
                map.put("pickupNum", entityXfRecordProcess.getReceiptNo());
                map.put("orderTime", DateUtil.getDateTime(entityXfRecordProcess.getPayTime()));
                map.put("opTypeDiff", entityXfRecordProcess.getOpTypeDiff());
                return ResultUtil.success(map);
            } else if (entityXfRecordProcess.getPayState() == 2) {
                //支付失败
                return ResultUtil.error(ResultEnum.Err_3030);
            } else {
                //查询配置信息向统一平台发起支付
                EntiyXfMerchPayInfo entiyXfMerchPayInfo = payHandleFunService.configure(entityXfRecordProcess);

                if (entiyXfMerchPayInfo == null) {
                    //商户支付渠道未配置"
                    return ResultUtil.error(ResultEnum.Err_3048);
                }

                Map<String, Object> retMap = new HashMap<>();
                retMap.put("company_id", entiyXfMerchPayInfo.getCompanyId());
                retMap.put("user_name", entiyXfMerchPayInfo.getUserName());
                retMap.put("password", entiyXfMerchPayInfo.getPassword());
                retMap.put("pos_no", machno);
                retMap.put("out_trade_no", tradeNo);

                String json= "";
                JSONObject results = null;
                try {
                    //向统一支付平台发起支付
                    String payUrl = companyInfoService.getPayCenterUrl(companyID, entiyXfMerchPayInfo.getCompanyId());
//                    String ma = JSON.toJSONString(retMap);
                    json = HttpUtils.postsJson(payUrl + "/unifiedmicropay/select.do", retMap);
                    results = JSON.parseObject(json);
                }catch (Exception e){
                    log.info("请求方式380:【{}】,机器号:【{}】,统一支付调用异常:【{}】,异常后返回状态:【{}】","支付请求（强在线）", entityXfRecordProcess.getDeviceNo(),e,json);
                    //支付结果未知
                    return ResultUtil.error(ResultEnum.Err_3029);
                }

//                EntityXfRecordProcess updateXfRecordProcess = new EntityXfRecordProcess();
//                updateXfRecordProcess.setId(entityXfRecordProcess.getId());
                entityXfRecordProcess.setPayChannelNo(entiyXfMerchPayInfo.getCompanyId());
                if (results.getInteger("code") == 200) {
                    Map<String, String> dataMap = (Map<String, String>) JSON.parse(results.getString("data"));
                    if (dataMap.get("trade_status").equals("SUCCESS")) {
                        //支付成功，修改等待表的状态和把数据入成功表
                        entityXfRecordProcess.setChannelOrderNo(dataMap.get("trade_no"));
                        entityXfRecordProcess.setPayState(1);
                        if (!dataMap.get("pay_code_type").equals("")) {
                            entityXfRecordProcess.setOpTypeDiff(Long.valueOf(payCode(dataMap.get("pay_code_type"))));
                        }
                        entityXfRecordProcess.setPayWay(PayWar.getPayWar(dataMap.get("trade_type")));
                        entityXfRecordProcess.setPayTime(DateUtil.getDate(dataMap.get("time_end"), "yyyyMMddHHmmss"));
                        if (entityXfRecordProcess.getPayWay() == 31) {
                            JSONObject jsonObject = JSON.parseObject(dataMap.get("body"));
                            entityXfRecordProcess.setPCode(jsonObject.getString("idNo"));
                            entityXfRecordProcess.setPName(jsonObject.getString("userName"));
                            Integer realMoneyUse = Integer.valueOf(dataMap.get("total_amount")) * -1;
                            entityXfRecordProcess.setRealMoney(realMoneyUse.longValue());
                            entityXfRecordProcess.setPCode(jsonObject.getString("idNo"));
                            entityXfRecordProcess.setPName(jsonObject.getString("userName"));
                            entityXfRecordProcess.setRealMoney(realMoneyUse.longValue());
                        }
                        boolean upodateFlag = true;
                        try {
                            int i = xfRecordProcessService.updateEntityXfRecord(companyID, entityXfRecordProcess);
                            if (i <= 0) {
                                upodateFlag = false;
                                log.info("请求方式:【{}】,机器号:【{}】,入库修改的数据:【{}】,返回:【{}】", "付款码订单查询", machno, entityXfRecordProcess, "等待表修改入库失败");
                                log.info("请求方式:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "付款码订单查询", machno, retMap, json);
                            }
                        } catch (Exception e) {
                            upodateFlag = false;
                            StackTraceElement ste = e.getStackTrace()[0];
                            log.info("请求方式:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】", "付款码订单查询", machno, entityXfRecordProcess, e, ste.getLineNumber());
                            log.info("请求方式:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "付款码订单查询", machno, retMap, json);
                        }
                        //	entiyEntiyXfRecordProcess.setId(null);
                        if (upodateFlag) {
                            try {

                                String redOrdKey = "redisOrder:" + entityXfRecordProcess.getComId()+":"
                                        +entityXfRecordProcess.getOrderNo();

                                String toJson = JsonUtils.toJson(entityXfRecordProcess);
                                redisUtil.set(redOrdKey,toJson,500l);

                                MqSaveOrderVo mqSaveOrderVo = new MqSaveOrderVo();
                                mqSaveOrderVo.setComId(request.getCompanyId());
                                mqSaveOrderVo.setId(entityXfRecordProcess.getId());
                                mqSaveOrderVo.setMachNo(entityXfRecordProcess.getDeviceNo());
                                mqSaveOrderVo.setRedisOrderNo(redOrdKey);
                                saveOrderProductService.saveOrder(mqSaveOrderVo);
                            } catch (Exception e) {
                                StackTraceElement ste = e.getStackTrace()[0];
                                log.info("请求方式:【{}】,机器号:【{}】,被扫查询-入库新增菜品缓存表数据的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", machno, entityXfRecordProcess, e, ste.getLineNumber());
                            }
                        }
                        Map<String, Object> map = new HashMap<>();
                        map.put("discount", entityXfRecordProcess.getDiscount());
                        map.put("payAmount", entityXfRecordProcess.getRealMoney());
                        map.put("pickupNum", entityXfRecordProcess.getReceiptNo());
                        map.put("orderTime", DateUtil.getDateTime(entityXfRecordProcess.getPayTime()));
                        map.put("opTypeDiff", entityXfRecordProcess.getOpTypeDiff());
                        return ResultUtil.success(map);
                    } else if (dataMap.get("trade_status").equals("PAYERROR")) {
                        //支付失败
                        entityXfRecordProcess.setPayState(2);
                        try {
                            int i = xfRecordProcessService.updateEntityXfRecord(companyID, entityXfRecordProcess);
                            if (i <= 0) {
                                log.info("请求方式:【{}】,机器号:【{}】,入库修改的数据:【{}】,返回:【{}】", "付款码订单查询", machno, entityXfRecordProcess, "等待表修改入库失败");
                                log.info("请求方式:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "付款码订单查询", machno, retMap, json);
                            }
                        } catch (Exception e) {
                            StackTraceElement ste = e.getStackTrace()[0];
                            log.info("请求方式:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】", "付款码订单查询", machno, entityXfRecordProcess, e, ste.getLineNumber());
                            log.info("请求方式:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "付款码订单查询", machno, retMap, json);
                        }
                        return ResultUtil.error(ResultEnum.Err_3030);
                    } else if (dataMap.get("trade_status").equals("REVOKED") || dataMap.get("trade_status").equals("CLOSED")) {
                        //已撤单
                        entityXfRecordProcess.setPayState(4);
                        try {
                            int i = xfRecordProcessService.updateEntityXfRecord(companyID, entityXfRecordProcess);
                            if (i <= 0) {
                                log.info("请求方式:【{}】,机器号:【{}】,入库修改的数据:【{}】,返回:【{}】", "付款码订单查询", machno, entityXfRecordProcess, "等待表修改入库失败");
                                log.info("请求方式:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "付款码订单查询", machno, retMap, json);
                            }
                        } catch (Exception e) {
                            StackTraceElement ste = e.getStackTrace()[0];
                            log.info("请求方式:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】", "付款码订单查询", machno, entityXfRecordProcess, e, ste.getLineNumber());
                            log.info("请求方式:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "付款码订单查询", machno, retMap, json);
                        }
                        return ResultUtil.error(ResultEnum.Err_3033);
                    } else if (dataMap.get("trade_status").equals("REFUND")) {
                        //转入退款
                        entityXfRecordProcess.setPayState(5);
                        try {
                            int i = xfRecordProcessService.updateEntityXfRecord(companyID, entityXfRecordProcess);
                            if (i <= 0) {
                                log.info("请求方式:【{}】,机器号:【{}】,入库修改的数据:【{}】,返回:【{}】", "付款码订单查询", machno, entityXfRecordProcess, "等待表修改入库失败");
                                log.info("请求方式:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "付款码订单查询", machno, retMap, json);
                            }
                        } catch (Exception e) {
                            StackTraceElement ste = e.getStackTrace()[0];
                            log.info("请求方式:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】", "付款码订单查询", machno, entityXfRecordProcess, e, ste.getLineNumber());
                            log.info("请求方式:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "付款码订单查询", machno, retMap, json);
                        }
                        return ResultUtil.error(ResultEnum.Err_3034);
                    } else {
                        //log.info("请求方式:【{}】,机器号:【{}】,支付结果未知 :【{}】,返回:【{}】","付款码订单查询1",machno,updateXfRecordProcess,dataMap);
                        //支付结果未知
                        return ResultUtil.error(ResultEnum.Err_3029);
                    }
                } else if (results.getInteger("code") == 19 || results.getInteger("code") == 16
                        || results.getInteger("code") == 7) {
                    //log.info("请求方式:【{}】,机器号:【{}】,支付结果未知 :【{}】,返回:【{}】","付款码订单查询2",machno,updateXfRecordProcess,results);
                    //支付结果未知
                    return ResultUtil.error(ResultEnum.Err_3029);
                } else {
                    log.info("请求方式:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "付款码订单查询", machno, retMap, json);
                    return ResultUtil.error(ResultEnum.Err_3032);
                }
            }
        } catch (Exception e) {
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,异常:【{}】,行号:【{}】", "付款码订单查询", machno, request, e, ste.getLineNumber());
            return ResultUtil.error(ResultEnum.Err_3031);
        }
    }

    @Override
    public int useVoucherAndSubAccount(EntityXfRecordProcess entityXfRecordProcess,
                                          EntityConsTypeConfig entityConsTypeConfig,
                                          EntityXfDeviceMealConfig mealConfig,
                                          List<MachMealDataVo> menuData,
                                          FeePlanVo feePlanVo,
                                          EntityXfAccountInfo entityXfAccountInfo,
                                          EntityXfSubAccountList entityXfSubAccountList) {
        if(entityXfRecordProcess.getOrderNo().startsWith("DK")){
            entityXfRecordProcess.setOrderNo(entityXfRecordProcess.getOrderNo().substring(2));
        }
        if (feePlanVo != null) {
            entityXfRecordProcess.setVoucherNo(feePlanVo.getVoucherNo());
            entityXfRecordProcess.setVoucherType(feePlanVo.getVoucherType());
            entityXfRecordProcess.setParValue(feePlanVo.getVoucherFee());
            entityXfRecordProcess.setVoucherNumber(feePlanVo.getVoucherNumber());
            entityXfRecordProcess.setDeduction(feePlanVo.getVoucherDeduction());
            entityXfRecordProcess.setRealMoney(-1l*feePlanVo.getWalletFee().longValue());
        } else {
            feePlanVo = new FeePlanVo();
            feePlanVo.setWalletFee(Math.abs(entityXfRecordProcess.getRealMoney().intValue()));
        }

        entityXfRecordProcess.setSubMoney(0l);
        entityXfRecordProcess.setChargeMoney(0l);


        //非金额0  非计次
        if (entityXfRecordProcess.getRealMoney() != 0l && entityXfRecordProcess.getOpTypeDiff() != 0l) {

            if (entityConsTypeConfig.getSubAccount() == 0) {
                //工本费
                Long gbf = 0L;
                try {
                    gbf = xfAccountTypeService.selectGBF(entityXfRecordProcess.getComId(), entityXfAccountInfo.getAccTypeId());
                } catch (Exception exception) {
                    StackTraceElement ste = exception.getStackTrace()[0];
                    log.info("查找工本费异常 【{}】【{}】", ste.getLineNumber(), exception);
                }

                //字符串：空表示不允许使用虚拟账户扣款,扣款顺序（1现金钱包、2补贴钱包）
                entityXfRecordProcess.setChargeBalance(entityXfAccountInfo.getAccountRechargeMoney());
                entityXfRecordProcess.setSubBalance(entityXfAccountInfo.getAccountSubsidyMoney());
                String walletSerial = "21";
                if (entityConsTypeConfig != null) {
                    if (entityConsTypeConfig.getWalletSerial() != null) {
                        walletSerial = entityConsTypeConfig.getWalletSerial();
                    }
                }
                //判断余额是否足够
                Long  moneyEnough = entityXfRecordProcess.getRealMoney() + entityXfAccountInfo.getAccountSubsidyMoney()
                        + entityXfAccountInfo.getAccountSubsidyMoney() - gbf;
                if(moneyEnough<0l && walletSerial.contains("2")){
                    walletSerial = "21" ;
                }
                if (walletSerial.equals("2")) {
                    //补贴钱包
                    Long subBalance = entityXfRecordProcess.getRealMoney() + entityXfAccountInfo.getAccountSubsidyMoney();
                    entityXfRecordProcess.setSubBalance(subBalance);
                    entityXfRecordProcess.setChargeBalance(entityXfAccountInfo.getAccountRechargeMoney());
                    entityXfRecordProcess.setSubMoney(entityXfRecordProcess.getRealMoney());
                    entityXfRecordProcess.setChargeMoney(0L);
                } else if (walletSerial.equals("21")) {
                    //先扣补贴钱包，再扣现金钱包
                    Long subBalance = entityXfRecordProcess.getRealMoney() + entityXfAccountInfo.getAccountSubsidyMoney();
                    if (subBalance < 0) {
                        Long chargeBalance = subBalance + entityXfAccountInfo.getAccountRechargeMoney();
                        entityXfRecordProcess.setSubBalance(0L);
                        entityXfRecordProcess.setSubMoney(-entityXfAccountInfo.getAccountSubsidyMoney());
                        entityXfRecordProcess.setChargeBalance(chargeBalance);
                        entityXfRecordProcess.setChargeMoney(subBalance);
                    } else {
                        entityXfRecordProcess.setSubBalance(subBalance);
                        entityXfRecordProcess.setChargeBalance(entityXfAccountInfo.getAccountRechargeMoney());
                        entityXfRecordProcess.setSubMoney(entityXfRecordProcess.getRealMoney());
                        entityXfRecordProcess.setChargeMoney(0L);
                    }
                } else if (walletSerial.equals("12")) {
                    //先扣现金钱包，再扣补贴钱包
                    Long chargeBalance = entityXfRecordProcess.getRealMoney() + entityXfAccountInfo.getAccountRechargeMoney() - gbf;
                    if (chargeBalance < 0) {
                        Long subBalance = chargeBalance + entityXfAccountInfo.getAccountSubsidyMoney();
                        entityXfRecordProcess.setSubBalance(subBalance);
                        entityXfRecordProcess.setSubMoney(chargeBalance);
                        entityXfRecordProcess.setChargeBalance(gbf);
                        entityXfRecordProcess.setChargeMoney(-entityXfAccountInfo.getAccountRechargeMoney()+gbf);
                    } else {
                        entityXfRecordProcess.setSubBalance(entityXfAccountInfo.getAccountSubsidyMoney());
                        entityXfRecordProcess.setChargeBalance(chargeBalance+gbf);
                        entityXfRecordProcess.setChargeMoney(entityXfRecordProcess.getRealMoney());
                        entityXfRecordProcess.setSubMoney(0L);
                    }
                } else {
                    //现金钱包
                    Long chargeBalance = entityXfRecordProcess.getRealMoney() + entityXfAccountInfo.getAccountRechargeMoney();
                    entityXfRecordProcess.setSubBalance(entityXfAccountInfo.getAccountSubsidyMoney());
                    entityXfRecordProcess.setChargeBalance(chargeBalance);
                    entityXfRecordProcess.setChargeMoney(entityXfRecordProcess.getRealMoney());
                    entityXfRecordProcess.setSubMoney(0L);
                }
            } else {
                entityXfRecordProcess.setSubAccount(entityConsTypeConfig.getSubAccount());
                entityXfRecordProcess.setChargeBalance(entityXfSubAccountList.getAccountRechargeMoney().longValue());
                entityXfRecordProcess.setSubBalance(entityXfSubAccountList.getAccountSubsidyMoney().longValue());
                if (CommonUtil.isNull(entityXfRecordProcess.getReserved3())) {
                    entityXfRecordProcess.setReserved3("");  //准备记录钱包编号
                }
                entityXfRecordProcess.setReserved3(entityXfRecordProcess.getReserved3() + "#使用钱包编号:" + entityConsTypeConfig.getSubAccount());
                //字符串：空表示不允许使用虚拟账户扣款,扣款顺序（1现金钱包、2补贴钱包）
                String walletSerial = "21";
                if (entityConsTypeConfig != null) {
                    if (entityConsTypeConfig.getWalletSerial() != null) {
                        walletSerial = entityConsTypeConfig.getWalletSerial();
                    }
                }
                //判断余额是否足够
                Long  moneyEnough = entityXfRecordProcess.getRealMoney() + entityXfSubAccountList.getAccountSubsidyMoney()
                        + entityXfSubAccountList.getAccountSubsidyMoney() ;
                if(moneyEnough<0l && walletSerial.contains("2")){
                    walletSerial = "21" ;
                }
                if (walletSerial.equals("2")) {
                    //补贴钱包
                    Long subBalance = entityXfRecordProcess.getRealMoney() + entityXfSubAccountList.getAccountSubsidyMoney();
                    entityXfRecordProcess.setSubBalance(subBalance);
                    entityXfRecordProcess.setChargeBalance(entityXfSubAccountList.getAccountRechargeMoney().longValue());
                    entityXfRecordProcess.setSubMoney(entityXfRecordProcess.getRealMoney());
                    entityXfRecordProcess.setChargeMoney(0L);
                } else if (walletSerial.equals("21")) {
                    //先扣补贴钱包，再扣现金钱包
                    Long subBalance = entityXfRecordProcess.getRealMoney() + entityXfSubAccountList.getAccountSubsidyMoney();
                    if (subBalance < 0) {
                        Long chargeBalance = subBalance + entityXfSubAccountList.getAccountRechargeMoney();
                        entityXfRecordProcess.setSubBalance(0L);
                        entityXfRecordProcess.setSubMoney(-entityXfSubAccountList.getAccountSubsidyMoney().longValue());

                        entityXfRecordProcess.setChargeBalance(chargeBalance);
                        entityXfRecordProcess.setChargeMoney(subBalance);
                    } else {
                        entityXfRecordProcess.setSubBalance(subBalance);
                        entityXfRecordProcess.setChargeBalance(entityXfSubAccountList.getAccountRechargeMoney().longValue());
                        entityXfRecordProcess.setSubMoney(entityXfRecordProcess.getRealMoney());
                        entityXfRecordProcess.setChargeMoney(0L);
                    }
                } else if (walletSerial.equals("12")) {
                    //先扣现金钱包，再扣补贴钱包
                    Long chargeBalance = entityXfRecordProcess.getRealMoney() + entityXfSubAccountList.getAccountRechargeMoney();
                    if (chargeBalance < 0) {
                        Long subBalance = chargeBalance + entityXfSubAccountList.getAccountSubsidyMoney();
                        entityXfRecordProcess.setSubBalance(subBalance);
                        entityXfRecordProcess.setSubMoney(chargeBalance);
                        entityXfRecordProcess.setChargeBalance(0L);
                        entityXfRecordProcess.setChargeMoney(-entityXfSubAccountList.getAccountRechargeMoney().longValue());
                    } else {
                        entityXfRecordProcess.setSubBalance(entityXfSubAccountList.getAccountSubsidyMoney().longValue());
                        entityXfRecordProcess.setChargeBalance(chargeBalance);
                        entityXfRecordProcess.setChargeMoney(entityXfRecordProcess.getRealMoney());
                        entityXfRecordProcess.setSubMoney(0L);
                    }
                } else {
                    //现金钱包
                    Long chargeBalance = entityXfRecordProcess.getRealMoney() + entityXfSubAccountList.getAccountRechargeMoney();
                    entityXfRecordProcess.setSubBalance(entityXfSubAccountList.getAccountSubsidyMoney().longValue());
                    entityXfRecordProcess.setChargeBalance(chargeBalance);
                    entityXfRecordProcess.setChargeMoney(entityXfRecordProcess.getRealMoney());
                    entityXfRecordProcess.setSubMoney(0L);
                }
            }
        }else{
            if (entityConsTypeConfig==null || entityConsTypeConfig.getSubAccount() == 0) {
                //字符串：空表示不允许使用虚拟账户扣款,扣款顺序（1现金钱包、2补贴钱包）
                entityXfRecordProcess.setChargeBalance(entityXfAccountInfo.getAccountRechargeMoney());
                entityXfRecordProcess.setSubBalance(entityXfAccountInfo.getAccountSubsidyMoney());
            }else{
                entityXfRecordProcess.setChargeBalance(entityXfSubAccountList.getAccountRechargeMoney().longValue());
                entityXfRecordProcess.setSubBalance(entityXfSubAccountList.getAccountSubsidyMoney().longValue());
            }
        }

        try {
            if (entityXfRecordProcess.getPayState() == null) {
                //支付状态；0支付中、1支付成功，2支付失败，3撤单中，4已撤单，5退款中，6已退款，7部分退款成功
                entityXfRecordProcess.setPayState(0);
            }
            int i = xfRecordProcessService.insertEntityXfRecord(entityXfRecordProcess.getComId(), entityXfRecordProcess);
            if (i <= 0) {
                log.info("请求方式154:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（保存离线消费记录）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return -11;
            }
            try {
                EntityXfRecordProcessExtend entityXfRecordProcessExtend = new EntityXfRecordProcessExtend();
                entityXfRecordProcessExtend.setComId(entityXfRecordProcess.getComId());
                entityXfRecordProcessExtend.setOrderId(entityXfRecordProcess.getId());
                entityXfRecordProcessExtend.setOrderNo(entityXfRecordProcess.getOrderNo());
                xfRecordProcessExtendService.insertEntityXfRecordExtend(entityXfRecordProcess.getComId(), entityXfRecordProcessExtend);
            } catch (Exception e) {
                log.error("插入订单缓存扩展表失败  【{}】【{}】【{}】", entityXfRecordProcess.getComId(), entityXfRecordProcess.getOrderNo(), e);
            }

        } catch (Exception e) {
            Throwable cause = e.getCause();
            if (cause instanceof java.sql.SQLIntegrityConstraintViolationException) {
                //错误信息
                String errMsg = ((java.sql.SQLIntegrityConstraintViolationException) cause).getMessage();
                //根据约束名称定位是那个字段
                if (StringUtils.isNotBlank(errMsg) && errMsg.indexOf("order_no") != -1) {
                    return -11;
                }
            }
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式155:【{}】,机器号:【{}】,入库新增等待表的数据4:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（保存离线消费记录）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, e, ste.getLineNumber());
            log.info("请求方式156:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（保存离线消费记录）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, ResultUtil.error(ResultEnum.Err_900));
            //订单号重复
            return -11;
        }

        //2023年11月14日17:25:52 菜品缓存表
        try {
            if (menuData != null && menuData.size() > 0) {
                List<EntityXfGoodsListProcess> entityXfGoodsListProcesses = new ArrayList<>();
                if (entityXfRecordProcess.getMerchId() == null) entityXfRecordProcess.setMerchId(0l);
                if (entityXfRecordProcess.getDeptId() == null) entityXfRecordProcess.setDeptId(0l);
                if (entityXfRecordProcess.getPId() == null) entityXfRecordProcess.setPId(0l);
                for (MachMealDataVo menuDataVo : menuData) {
                    EntityXfGoodsListProcess entityXfGoodsListProcess = new EntityXfGoodsListProcess();
                    entityXfGoodsListProcess.setComId(entityXfRecordProcess.getComId());
                    entityXfGoodsListProcess.setDeviceNo(entityXfRecordProcess.getDeviceNo());
                    entityXfGoodsListProcess.setPointId(entityXfRecordProcess.getPointId().intValue());
                    entityXfGoodsListProcess.setMerchId(entityXfRecordProcess.getMerchId().intValue());
                    entityXfGoodsListProcess.setPId(entityXfRecordProcess.getPId().longValue());
                    entityXfGoodsListProcess.setDeptId(entityXfRecordProcess.getDeptId().intValue());
                    entityXfGoodsListProcess.setReceiptId(0);
                    entityXfGoodsListProcess.setReceiptName("");
                    entityXfGoodsListProcess.setOrderNo(entityXfRecordProcess.getOrderNo());
                    entityXfGoodsListProcess.setConsTime(DateUtils.strToDate3(menuDataVo.getEtime(), "yyyyMMddHHmmss"));
                    entityXfGoodsListProcess.setMealDate(entityXfRecordProcess.getMealDate());
                    entityXfGoodsListProcess.setMealNo(Integer.valueOf(entityXfRecordProcess.getMealNo()));
                    entityXfGoodsListProcess.setConsType(entityXfRecordProcess.getConsType());
                    entityXfGoodsListProcess.setIfRefund(0);
                    entityXfGoodsListProcess.setDishesId(menuDataVo.getDishesId());
                    entityXfGoodsListProcess.setDishesName(menuDataVo.getDishesName());
                    entityXfGoodsListProcess.setPriceMode(menuDataVo.getPriceMode());
                    entityXfGoodsListProcess.setWeightNumber(menuDataVo.getNum());
                    entityXfGoodsListProcess.setDishesPrice(menuDataVo.getPrice());
                    entityXfGoodsListProcess.setMonthValue(entityXfRecordProcess.getMonthValue());
                    entityXfGoodsListProcess.setCreateTime(new Date());

                    entityXfGoodsListProcesses.add(entityXfGoodsListProcess);
                }
                xfGoodsListProcessService.addXfGoodsListProcessList(entityXfRecordProcess.getComId(), entityXfGoodsListProcesses);
            }
        } catch (Exception e) {
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式157:【{}】,机器号:【{}】,入库菜品缓存表的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（保存离线消费记录）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, e, ste.getLineNumber());
            log.info("请求方式158:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（保存离线消费记录）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, ResultUtil.error(ResultEnum.Err_900));
        }

        try {
            Integer accountId = entityXfAccountInfo.getId();
            if (entityConsTypeConfig.getSubAccount() > 0) {
                accountId = entityXfSubAccountList.getId();
            }
            Boolean bo = xfRecordProcessService.saveLxOrder(entityXfRecordProcess.getComId(),entityXfRecordProcess, entityConsTypeConfig.getSubAccount(),accountId);
            if (!bo) {
                return -12;
            }
            entityXfRecordProcess.setPayWay(0);
            entityXfRecordProcess.setPayState(1);
            entityXfRecordProcess.setPayTime(new Date());
        } catch (Exception e) {
            log.info("请求方式199:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（保存离线消费记录）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, e);
            return -12;
        }
        try {
            String redOrdKey = "redisOrder:" + entityXfRecordProcess.getComId()+":"
                    +entityXfRecordProcess.getOrderNo();

            String toJson = JsonUtils.toJson(entityXfRecordProcess);
            redisUtil.set(redOrdKey,toJson,500l);

            MqSaveOrderVo mqSaveOrderVo=new MqSaveOrderVo();
            mqSaveOrderVo.setComId(entityXfRecordProcess.getComId());
            mqSaveOrderVo.setId(entityXfRecordProcess.getId());
            mqSaveOrderVo.setMachNo(entityXfRecordProcess.getDeviceNo());
            mqSaveOrderVo.setRedisOrderNo(redOrdKey);
            saveOrderProductService.saveOrder(mqSaveOrderVo);
        } catch (Exception e) {
            log.info("请求方式 KNWY6t7kCt 操作mq异常:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（保存离线消费记录）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, e);
        }
        return 1;

    }

    @Override
    public FeePlanVo getVoucherUse(EntityXfRecordProcess entityXfRecordProcess,
                                   EntityConsTypeConfig entityConsTypeConfig,
                                   EntityXfDeviceMealConfig mealConfig,
                                   List<MachMealDataVo> menuData,
                                   Integer walletBalance) {


        FeePlanVo feePlanVo = new FeePlanVo();
        feePlanVo.setWalletFee(Math.abs(entityXfRecordProcess.getRealMoney().intValue()));
        //金额0 不需要用金额和优惠券
        if (entityXfRecordProcess.getRealMoney() == 0l) {
            return feePlanVo;
        }

        if (mealConfig == null ||
                CommonUtil.isNull(mealConfig.getVoucherTypes()) ||
                (mealConfig.getVoucherMode() != 2 && mealConfig.getVoucherMode() != 3)) {
            return feePlanVo;
        }

        //计算时区
        Integer timeZone = 0;
        try {
            ConsTimeZoneVo consTimeZoneVo = xfZoneDateService.getTimeZone(entityXfRecordProcess.getComId(), entityXfRecordProcess.getConsTime());
            timeZone = consTimeZoneVo.getConsTimeZone();
        } catch (Exception e1) {
            log.error("查时区异常12【{}】【{}】", entityXfRecordProcess, e1);
        }

        //先使用优惠券 再余额

        List<VoucherListVo> voucherListVoList = voucherDataService.selectVoucherList(entityXfRecordProcess.getComId(),
                entityXfRecordProcess.getPId(),
                entityXfRecordProcess.getConsTime(),
                mealConfig.getVoucherTypes(),
                timeZone,
                entityXfRecordProcess.getConsType());
        if (voucherListVoList == null || voucherListVoList.size() == 0) {
            return feePlanVo;
        }
        Long realPayMoney = Math.abs(entityXfRecordProcess.getRealMoney());

        //2、
        Boolean bPart = false;//（没有指定菜品的消费券）。

        for (int i = 0; i < voucherListVoList.size(); i++) {
            VoucherListVo listVo = voucherListVoList.get(i);
            if (CommonUtil.isNull(listVo.getDishes())) {
                listVo.setLevel(2);
            } else {
                //可用范围
                String[] items = listVo.getDishes().split(",");
                List<Integer> dishesList = Stream.of(items).map(Integer::parseInt).collect(Collectors.toList());
                for (MachMealDataVo menuDataVo : menuData) {
                    if (dishesList.contains(menuDataVo.getDishesId())) {
                        listVo.setPartMoney(listVo.getPartMoney() + menuDataVo.getPrice());
                    }
                }
                if (listVo.getPartMoney() == 0) {
                    listVo.setLevel(0);
                } else {
                    listVo.setLevel(1);
                    bPart = true;
                    listVo.setAppointDishes(true);
                }
                voucherListVoList.set(i, listVo);
            }
        }

        //5、如果bPart == false跳转6

        if (bPart) {
            //5a 小额
            if (mealConfig.getVoucherMode() == 3) {
                for (VoucherListVo voucherListVo : voucherListVoList) {
                    if (voucherListVo.getLevel() != 1) {
                        continue;
                    }
                    Integer wFee = realPayMoney.intValue(); //支付金额
                    Integer vFee = 0;   //券金额
                    Integer vNum = 0;  //使用张数


                    while (vNum.compareTo(voucherListVo.getRemainNumber()) < 0 && wFee.compareTo(voucherListVo.getParValue()) >= 0) {
                        wFee -= voucherListVo.getParValue();
                        vFee += voucherListVo.getParValue();
                        vNum++;
                    }

                    //使用现金钱包最少得套餐
                    if (wFee.compareTo(feePlanVo.getWalletFee()) < 0) {
                        feePlanVo.setWalletFee(wFee);
                        feePlanVo.setVoucherFee(vFee);
                        feePlanVo.setVoucherNumber(vNum);
                        feePlanVo.setVoucherNo(voucherListVo.getVoucherNo());
                        feePlanVo.setVoucherType(voucherListVo.getVoucherType());
                        feePlanVo.setVoucherDeduction(vFee);
                    }
                }
                if (feePlanVo.getWalletFee().compareTo(walletBalance) <= 0) {
                    return feePlanVo;
                }
            }
            //5b 任意
            for (VoucherListVo voucherListVo : voucherListVoList) {
                if (voucherListVo.getLevel() != 1) {
                    continue;
                }
                Integer wFee = realPayMoney.intValue(); //支付金额
                Integer vFee = 0;   //券金额
                Integer vNum = 0;  //使用张数
                Integer deductionFee = 0;   //抵扣金额

    //            Integer partFee = voucherListVo.getPartMoney().compareTo(wFee) > 0 ? wFee : voucherListVo.getPartMoney();
                while (vNum.compareTo(voucherListVo.getRemainNumber()) < 0) {
                    wFee -= voucherListVo.getParValue();
  //                  partFee -= voucherListVo.getParValue();
                    vFee += voucherListVo.getParValue();
                    vNum++;
                    if (wFee <= 0) {
                        break;
                    }
                }

//                if (partFee < 0) {
//                    wFee = realPayMoney.intValue() - voucherListVo.getPartMoney();
//                }
                if (wFee < 0) {
                    wFee = 0;
                    deductionFee = realPayMoney.intValue();
                }else{
                    deductionFee = vFee;
                }


                //使用现金钱包最少得套餐
                if (wFee.compareTo(feePlanVo.getWalletFee()) < 0
                        || (wFee.equals(feePlanVo.getWalletFee()) && vFee.compareTo(feePlanVo.getVoucherFee()) < 0)) {
                    feePlanVo.setWalletFee(wFee);
                    feePlanVo.setVoucherFee(vFee);
                    feePlanVo.setVoucherNumber(vNum);
                    feePlanVo.setVoucherNo(voucherListVo.getVoucherNo());
                    feePlanVo.setVoucherType(voucherListVo.getVoucherType());
                    feePlanVo.setVoucherDeduction(deductionFee);
                }
            }
            if (feePlanVo.getWalletFee().compareTo(walletBalance) <= 0) {
                return feePlanVo;
            }
        }
        // 6 6 6 只找不指定菜品的消费券
        if (mealConfig.getVoucherMode() == 3) {
            for (VoucherListVo voucherListVo : voucherListVoList) {
                if (voucherListVo.getLevel() != 2) {
                    continue;
                }
                Integer wFee = realPayMoney.intValue(); //支付金额
                Integer vFee = 0;   //券金额
                Integer vNum = 0;  //使用张数

                while (vNum.compareTo(voucherListVo.getRemainNumber()) < 0 && wFee.compareTo(voucherListVo.getParValue()) >= 0) {
                    wFee -= voucherListVo.getParValue();
                    vFee += voucherListVo.getParValue();
                    vNum++;
                }

                //使用现金钱包最少得套餐
                if (wFee.compareTo(feePlanVo.getWalletFee()) <= 0) {
                    feePlanVo.setWalletFee(wFee);
                    feePlanVo.setVoucherFee(vFee);
                    feePlanVo.setVoucherNumber(vNum);
                    feePlanVo.setVoucherNo(voucherListVo.getVoucherNo());
                    feePlanVo.setVoucherType(voucherListVo.getVoucherType());
                    feePlanVo.setVoucherDeduction(vFee);
                }
            }
            if (feePlanVo.getWalletFee().compareTo(walletBalance) <= 0) {
                return feePlanVo;
            }
        }

        for (VoucherListVo voucherListVo : voucherListVoList) {
            if (voucherListVo.getLevel() != 2) {
                continue;
            }
            Integer wFee = realPayMoney.intValue(); //支付金额
            Integer vFee = 0;   //券金额
            Integer vNum = 0;  //使用张数
            Integer deductionFee = 0;   //抵扣金额

            while (vNum.compareTo(voucherListVo.getRemainNumber()) < 0) {
                wFee -= voucherListVo.getParValue();
                vFee += voucherListVo.getParValue();
                vNum++;
                if (wFee <= 0) {
                    break;
                }
            }
            if (wFee < 0) {
                wFee = 0;
                deductionFee = realPayMoney.intValue();
            }else{
                deductionFee = vFee;
            }

            //使用现金钱包最少得套餐
            if (wFee.compareTo(feePlanVo.getWalletFee()) < 0 ||
                    (wFee.compareTo(feePlanVo.getWalletFee()) == 0 && vFee.compareTo(feePlanVo.getVoucherFee()) < 0)) {
                feePlanVo.setWalletFee(wFee);
                feePlanVo.setVoucherFee(vFee);
                feePlanVo.setVoucherNumber(vNum);
                feePlanVo.setVoucherNo(voucherListVo.getVoucherNo());
                feePlanVo.setVoucherType(voucherListVo.getVoucherType());
                feePlanVo.setVoucherDeduction(deductionFee);
            }
        }
        if (feePlanVo.getWalletFee().compareTo(walletBalance) <= 0) {
            return feePlanVo;
        }
        return feePlanVo;
    }


    //payType 订单处理方式  默认1    2厦门订餐发起代扣  3定时任务发起代扣
    public int withholding(EntityXfRecordProcess entityXfRecordProcess, QrCardPayRequest request,
                           EntityCardInfo entityCardInfo, JSONObject jsonObject,Integer payType){
        if(!entityXfRecordProcess.getOrderNo().startsWith("LX") && !entityXfRecordProcess.getOrderNo().startsWith("BJ")
                && payType==1 ){
            entityXfRecordProcess.setOrderNo("DK"+ request.getTradeNo());
        }
        boolean withholdSubmerch=false;
        int parentMerchId= Math.toIntExact(entityXfRecordProcess.getMerchId());
        //状态流程
        List<EntityXfChannelInfo> xfChannelInfoList=null;
        //判断收费点为空和为0是按单位查询
        if (entityXfRecordProcess.getPointId()==null || entityXfRecordProcess.getPointId()==0 || entityXfRecordProcess.getMerchId()==null
                || entityXfRecordProcess.getMerchId()==0l
        ){
            xfChannelInfoList=xfChannelInfoService.selectPayWay(entityXfRecordProcess.getComId(),0L);
        }else {
            //a)pMerID:=merchID，查找商户pMerID有没有支付通道，如果没有找上级商户，直至顶级（pMerID ==0）。
            xfChannelInfoList = xfChannelInfoService.selectPayWay(entityXfRecordProcess.getComId(), entityXfRecordProcess.getMerchId());
//            log.info("查签约号-当前商户 【{}】【{}】", entityXfRecordProcess.getMerchId(), xfChannelInfoList);

            //当前商户信息 判断是否需要上级商户
            EntityXfMerchantInfo currentXfMerchantInfo = xfMerchantInfoService.selectParentMerchId(entityXfRecordProcess.getComId(), parentMerchId);
            withholdSubmerch = currentXfMerchantInfo.getWithholdSubmerch();

            if (xfChannelInfoList == null || xfChannelInfoList.size() <= 0 ||
                    //或者要用商户服务商数据
                    (currentXfMerchantInfo != null && currentXfMerchantInfo.getWithholdSubmerch() == true)
            ) {
                parentMerchId = currentXfMerchantInfo.getParentMerchId();
                for (int i = 0; i < 10; i++) {
                    EntityXfMerchantInfo entityXfMerchantInfo = xfMerchantInfoService.selectParentMerchId(entityXfRecordProcess.getComId(), parentMerchId);
//                    log.info("查签约号-上级商户 【{}】【{}】", parentMerchId, entityXfMerchantInfo);
                    //当前商户id判断
                    if (entityXfMerchantInfo != null && entityXfMerchantInfo.getParentMerchId() != null) {
                        if (entityXfMerchantInfo.getWithholdSubmerch()) {
                            parentMerchId = entityXfMerchantInfo.getParentMerchId();
                            if (parentMerchId == 0) {
                                break;
                            }
                            continue;
                        }
                        xfChannelInfoList = xfChannelInfoService.selectPayWay(entityXfRecordProcess.getComId(), Integer.valueOf(parentMerchId).longValue());
                        if (xfChannelInfoList != null && xfChannelInfoList.size() > 0) {
                            break;
                        } else {
                            parentMerchId = entityXfMerchantInfo.getParentMerchId();
                        }
                    }
                    //父级商户id为0不用循环下去了
                    if (parentMerchId == 0) {
                        break;
                    }
                }
            }
        }

        if (xfChannelInfoList==null || xfChannelInfoList.size()<=0){
            return -1;
        }


        EntityXfSignNo xfSignNo=null;
        EntityXfSignNo entityXfSignNo =null;

        if(request.getType()==9){

            entityXfSignNo =new EntityXfSignNo();
            entityXfSignNo.setSignNo("");
            entityXfSignNo.setPayWay(28);
            xfSignNo =new EntityXfSignNo();
            xfSignNo.setPayWay(28);
            entityXfRecordProcess.setOpTypeDiff(308L);
            entityXfRecordProcess.setOpType(22L);
        }else{
            Integer payWay = null;
            if (request.getType() == 21 ||  request.getType() == 22) {
                payWay = 32;
            }
            //如果holdwith_submerch==1，则pMerID:= parent_merch_id
            if (withholdSubmerch){
                entityXfSignNo =xfSignNoService.selectSignNo(entityXfRecordProcess.getComId(), Long.valueOf(parentMerchId), entityXfRecordProcess.getPId(),payWay);
            }else {
                entityXfSignNo =xfSignNoService.selectSignNo(entityXfRecordProcess.getComId(), entityXfRecordProcess.getMerchId(), entityXfRecordProcess.getPId(),payWay);
            }
//            log.info("查签约号-返回 【{}】【{}】",withholdSubmerch,entityXfSignNo);

            //查询代扣的签约号

            if (entityXfSignNo == null) {
                //代扣未签约"
                return -2;
            }

            //获取所签约的渠道
            xfSignNo=null;

            for (EntityXfChannelInfo entityXfChannelInfo : xfChannelInfoList) {
                if (entityXfChannelInfo.getPayWay().compareTo(entityXfSignNo.getPayWay()) ==0){
                    xfSignNo=entityXfSignNo;
                }
            }

//            log.info("查签约号-代扣签约 【{}】【{}】",xfSignNo,xfChannelInfoList);


            if (xfSignNo==null){
                return -2;
            }

            //306:建行数字货币代扣,307工行代扣 301 微信代扣
            if (xfSignNo.getPayWay()!=null){
                if (xfSignNo.getPayWay()==7){
                    entityXfRecordProcess.setOpTypeDiff(306L);
                }else if (xfSignNo.getPayWay()==3){
                    entityXfRecordProcess.setOpTypeDiff(307L);
                }else if (xfSignNo.getPayWay()==16){
                    entityXfRecordProcess.setOpTypeDiff(301L);
                }else if (xfSignNo.getPayWay()==28){
                    entityXfRecordProcess.setOpTypeDiff(308L);
                }else if (xfSignNo.getPayWay()==37){
                    //兰州银行
                    entityXfRecordProcess.setOpTypeDiff(Long.valueOf(OpTypeDiffEnum.LanbZhouDK.getIndex()));
                } else if (xfSignNo.getPayWay() == 32) {
                    try {
                        return CCBWithhold(entityXfRecordProcess, request,
                                entityCardInfo, jsonObject, xfSignNo);
                    } catch (Exception exception) {
                        log.info("【建行生活】【代扣】【异常】参数【{}】缓存数据【{}】异常【{}】", request, entityXfRecordProcess, exception);
                        return 0;
                    }
                }
                entityXfRecordProcess.setPayWay(xfSignNo.getPayWay());
            }

        }

        EntityXfRecordProcessExtend entityXfRecordProcessExtend = null;

        if(payType==1) {
            try {
                int i = xfRecordProcessService.insertEntityXfRecord(request.getCompanyId(), entityXfRecordProcess);
                if (i <= 0) {
                    log.error("请求方式74:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线,代扣）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
                    //订单号重复
                    return -11;
                }
                if(entityXfRecordProcess.getDiscount()!=null && entityXfRecordProcess.getDiscount()>0l) {
                    try {
                        entityXfRecordProcessExtend = new EntityXfRecordProcessExtend();
                        entityXfRecordProcessExtend.setComId(request.getCompanyId());
                        entityXfRecordProcessExtend.setOrderId(entityXfRecordProcess.getId());
                        entityXfRecordProcessExtend.setOrderNo(entityXfRecordProcess.getOrderNo());
                        xfRecordProcessExtendService.insertEntityXfRecordExtend(request.getCompanyId(), entityXfRecordProcessExtend);
                    } catch (Exception e) {
                        log.error("插入订单缓存扩展表失败  【{}】【{}】【{}】", request.getCompanyId(), request, e);
                    }
                }
            } catch (Exception e) {
                StackTraceElement ste = e.getStackTrace()[0];
                log.info("请求方式75:【{}】,机器号:【{}】,入库新增等待表的数据10:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线,代扣）", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
                log.info("请求方式76:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线,代扣）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return -11;
            }
            try {
                if(request.getConsState()==3 || request.getConsState()==5){
                    xfGoodsListProcessService.saveXfGoodsList(request.getCompanyId(), entityXfRecordProcess,request.getMealData());
                }
            }catch (Exception e){
                StackTraceElement ste =e.getStackTrace()[0];
                log.info("请求方式77:【{}】,机器号:【{}】,代扣-入库新增菜品缓存表数据的数据:【{}】,异常的返回:【{}】,行号:【{}】","支付请求（强在线）",request.getMachNo(), entityXfRecordProcess,e,ste.getLineNumber());
            }
        }
        if (entityCardInfo!=null){
            //修改卡流水和消费金额
            xfCardInfoService.upateCardMoneyA(request.getCompanyId(),entityCardInfo);
        }
        try {
            //查询配置信息
            EntiyXfMerchPayInfo entiyXfMerchPayInfo=payHandleFunService.configure(entityXfRecordProcess);
            if (entiyXfMerchPayInfo ==null){
                //商户支付渠道未配置"
                return -1;
            }

            //代扣
            SignNoHandle signNoHandle =new SignNoHandle();
            String signNo = signNoHandle.decrypt(entityXfSignNo.getSignNo(), entityXfRecordProcess.getComId());
            Map<String,Object> retMap=new HashMap<>();
            retMap.put("company_id",entiyXfMerchPayInfo.getCompanyId());
            retMap.put("user_name",entiyXfMerchPayInfo.getUserName());
            retMap.put("password",entiyXfMerchPayInfo.getPassword());
            retMap.put("pos_no", entityXfRecordProcess.getDeviceNo());
            retMap.put("fee_type","CNY");
            retMap.put("subject","代扣支付:"+ entityXfRecordProcess.getDeviceNo());
            retMap.put("out_trade_no", entityXfRecordProcess.getOrderNo());
            retMap.put("contract_id", signNo);
            retMap.put("total_amount", String.valueOf(Math.abs(entityXfRecordProcess.getRealMoney())));
            retMap.put("devsnip", "10.68.132.244");
            retMap.put("body","代扣支付");
            retMap.put("pay_channel",String.valueOf(xfSignNo.getPayWay()));
            retMap.put("tradeTime", DateUtils.getStrDate(entityXfRecordProcess.getConsTime(),"yyyy-MM-dd HH:mm:ss"));
            retMap.put("user_id", String.valueOf(entityXfRecordProcess.getPId()));
            retMap.put("lineSymbol","0");
            if(xfSignNo.getPayWay()==16 || xfSignNo.getPayWay()==28){
                retMap.put("user_id", request.getFaceToken());
            }
            if(xfSignNo.getPayWay()==28){
                retMap.put("pay_channel", "28");
                retMap.put("contract_id", request.getUId());
                retMap.put("aliSignInfo", request.getIotSignInfo());
                retMap.put("lineSymbol", 1);
            }

            //数据准备
//            EntityXfRecordProcess updateXfRecordProcess=new EntityXfRecordProcess();
//            updateXfRecordProcess.setId(entityXfRecordProcess.getId());
            entityXfRecordProcess.setPayChannelNo(entiyXfMerchPayInfo.getCompanyId());
//            entityXfRecordProcess.setComId(entityXfRecordProcess.getComId());

            //向统一支付平台发起支付
            String json = "";

            JSONObject results = null;
            int cancelConfig = -1;
            String canKey = "onlinePayCard:discountPaying#comId:"+request.getCompanyId()+"#pId:"+entityXfRecordProcess.getPId();
            try {
                String payUrl = companyInfoService.getPayCenterUrl(request.getCompanyId(), entiyXfMerchPayInfo.getCompanyId());
                if (entityXfRecordProcess.getDiscount() != null && entityXfRecordProcess.getDiscount() != 0) {
                    cancelConfig = payHandleFunService.getCancelConfig(request.getCompanyId(),entityXfRecordProcess.getOpTypeDiff());
                }
                if(cancelConfig>0){
                    json= HttpUtils.postJsonTimeOut(payUrl+"/withholding/pay.do",retMap,cancelConfig);
                }else{
                    json= HttpUtils.postJsonTimeOut(payUrl+"/withholding/pay.do",retMap,18);
                }
                results= JSON.parseObject(json);
            }catch (Exception e){
                if(payType == 1) {
                    log.info("请求方式280:【{}】,机器号:【{}】,统一支付调用异常:【{}】,异常的返回:【{}】", "支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), e, json);
                    //支付结果未知
                    int waitPayStatus = waitPayOnline(entityXfRecordProcess, request, entityXfRecordProcess);
                    if (waitPayStatus == 1) {
                        log.info("请求方式281:【{}】,机器号:【{}】,统一支付调用异常:【{}】,异常的返回:【{}】", "支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), e, waitPayStatus);
                        return waitPayStatus;
                    }
                }
                //超时代扣退款 更新为退
                if(payType == 1 && cancelConfig>0 && entityXfRecordProcessExtend!=null &&
                        entityXfRecordProcess.getDiscount()!=null && entityXfRecordProcess.getDiscount()!=0l){
                    try {
                        entityXfRecordProcessExtend.setCancelState(2);
                        boolean ins = xfRecordProcessExtendService.updateEntityXfRecordExtend(request.getCompanyId(), entityXfRecordProcessExtend);
                        if (ins){
                            redisUtil.zRemove(canKey, request.getTradeNo());
                            return -22;
                        }
                    }catch (Exception e4) {
                        log.error("更改为退款异常,【{}】【{}】【{}】",request,entityXfRecordProcessExtend,e4);
                    }
                }
                return 0;
            }


            if (results.getInteger("code")==200){
                //支付成功，修改等待表的状态和把数据入成功表
                Map<String,String> dataMap= (Map<String, String>) JSON.parse(results.getString("data"));
                entityXfRecordProcess.setChannelOrderNo(dataMap.get("trade_no"));
                entityXfRecordProcess.setPayTime(DateUtil.getDate(dataMap.get("time_end"),"yyyyMMddHHmmss"));
                entityXfRecordProcess.setPayState(1);
                if(payType == 3) entityXfRecordProcess.setConsState(5);
                entityXfRecordProcess.setPayWay(PayWar.getPayWar(dataMap.get("trade_type")));
                if(!CommonUtil.isNull(dataMap.get("body"))){
                    if(dataMap.get("body").startsWith("dianzi")){
                        entityXfRecordProcess.setReserved3("支付宝垫资");
                    }
                }
                try {
                    int i=xfRecordProcessService.updateEntityXfRecord(entityXfRecordProcess.getComId(),entityXfRecordProcess);
                    if (i<=0){
                        log.info("请求方式78:【{}】,机器号:【{}】,入库修改的数据:【{}】,返回:【{}】","支付请求（强在线）", entityXfRecordProcess.getDeviceNo(),entityXfRecordProcess,"等待表修改入库失败");
                        log.info("请求方式79:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】","支付请求（强在线）", entityXfRecordProcess.getDeviceNo(),retMap,json);
                    }
                }catch (Exception e){
                    StackTraceElement ste =e.getStackTrace()[0];
                    log.info("请求方式80:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】","支付请求（强在线）", entityXfRecordProcess.getDeviceNo(),entityXfRecordProcess,e,ste.getLineNumber());
                    log.info("请求方式81:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】","支付请求（强在线）", entityXfRecordProcess.getDeviceNo(),retMap,json);
                }

                try {

                    String redOrdKey = "redisOrder:" + entityXfRecordProcess.getComId()+":"
                            +entityXfRecordProcess.getOrderNo();

                    String toJson = JsonUtils.toJson(entityXfRecordProcess);
                    redisUtil.set(redOrdKey,toJson,500l);

                    MqSaveOrderVo mqSaveOrderVo = new MqSaveOrderVo();
                    mqSaveOrderVo.setComId(request.getCompanyId());
                    mqSaveOrderVo.setId(entityXfRecordProcess.getId());
                    mqSaveOrderVo.setMachNo(entityXfRecordProcess.getDeviceNo());
                    mqSaveOrderVo.setRedisOrderNo(redOrdKey);
                    if(payType == 3) mqSaveOrderVo.setType(3);
                    saveOrderProductService.saveOrder(mqSaveOrderVo);
                } catch (Exception e) {
                    StackTraceElement ste = e.getStackTrace()[0];
                    log.info("请求方式1002:【{}】,机器号:【{}】,代扣-插成功库:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, e, ste.getLineNumber());
                }
                if(payType == 1) {
                    try {
                        if (request.getConsState() == 3 || request.getConsState() == 5) {
                            xfGoodsListProcessService.saveXfGoodsListRecode(request.getCompanyId(), entityXfRecordProcess.getOrderNo());
                        }
                    } catch (Exception e) {
                        StackTraceElement ste = e.getStackTrace()[0];
                        log.info("请求方式84:【{}】,机器号:【{}】,代扣-入库新增菜品成功表数据的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
                    }
                }
                return 1;
            }else if (results.getInteger("code")==16 || results.getInteger("code")==19
                    || results.getInteger("code")==7  || results.getInteger("code")==6 || json.contains("Exception")){
                if(payType == 1) {
                    //支付结果未知 默认是返回0
                    int waitPayStatus = waitPayOnline(entityXfRecordProcess, request, entityXfRecordProcess);
                    log.info("请求方式283:【{}】,机器号:【{}】,统一支付返回支付中,当前的返回状态码:【{}】，当前的返回状态码:【{}】", "支付请求（强在线）", entityXfRecordProcess.getDeviceNo(),results, waitPayStatus);
                    if (waitPayStatus == 1) return waitPayStatus;
                }
                //超时代扣退款 更新为退
                if(payType == 1 && cancelConfig>0 && entityXfRecordProcessExtend!=null &&
                        entityXfRecordProcess.getDiscount()!=null && entityXfRecordProcess.getDiscount()!=0l){
                   try {
                       entityXfRecordProcessExtend.setCancelState(2);
                       boolean ins = xfRecordProcessExtendService.updateEntityXfRecordExtend(request.getCompanyId(), entityXfRecordProcessExtend);
                       if (ins){
                           redisUtil.zRemove(canKey, request.getTradeNo());
                           return -22;
                       }
                   }catch (Exception e) {
                        log.error("更改为退款异常,【{}】【{}】【{}】",request,entityXfRecordProcessExtend,e);
                   }
                }
                return 0;
            }else {
                try {
                    if(results.getInteger("code")==300
                    && results.getString("msg")!= null  && results.getString("msg").startsWith("钱包余额不足")  ){
                        EntityCompanyConfig entityCompanyConfig = companyConfigService.getTapValue(request.getCompanyId(), "insufficientBalanceMsg");
                        if (entityCompanyConfig != null && entityCompanyConfig.getConfig().equals("true")) {
                            String phone = xfSignOrderService.getSignPhone(entityXfRecordProcess.getComId(),entityXfRecordProcess.getMerchId(),entityXfRecordProcess.getPId());
                            if(phone!=null){
                                String insufficientBalanceMsg = "insufficientBalanceMsg:" + request.getCompanyId() + ":" + phone;
                                if (redisUtil.lock(insufficientBalanceMsg, 60 * 60)) {
                                    SmsRequest smsRequest = new SmsRequest();
                                    smsRequest.setSecretId("AKIDcLzhN0a8e8eChEnaQG8zpifcabfnu5JX");
                                    smsRequest.setSecretKey("Kh6VozznPn13ECwSlphN9jCVaRLTPIPa");
                                    smsRequest.setSignName("鑫澳康科技");
                                    smsRequest.setSdkAppId("1400314290");
                                    smsRequest.setTemplateId("2179744");
                                    smsRequest.setPhone(phone);
                                    mqSimpleFeign.FySms(smsRequest);
                                }
                            }
                        }
                    }
                }catch (Exception e){
                    log.info("余额不足发送短信异常 【】 ",e);
                }

                entityXfRecordProcess.setPayState(2);
                if(payType == 3) {
                    entityXfRecordProcess.setPayState(4);
                    entityXfRecordProcess.setIfRefund(1l);
                }

                if(results.getString("msg")!=null){
                    if(results.getString("msg").length()>49) results.put("msg",results.getString("msg").substring(0,45));
                    entityXfRecordProcess.setReserved2(results.getString("msg"));
                }

                if(payType==1) {
                    int waitPayStatus  = waitPayOnline(entityXfRecordProcess,request,entityXfRecordProcess);
                    if(waitPayStatus>0){
                        return waitPayStatus;
                    }
                }
                try {
                    int i=xfRecordProcessService.updateEntityXfRecord(entityXfRecordProcess.getComId(),entityXfRecordProcess);
                    if (i<=0){
                        log.info("请求方式85:【{}】,机器号:【{}】,入库修改的数据:【{}】,返回:【{}】","支付请求（强在线）", entityXfRecordProcess.getDeviceNo(),entityXfRecordProcess,"等待表修改入库失败");
                        log.info("请求方式86:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】","支付请求（强在线）", entityXfRecordProcess.getDeviceNo(),retMap,json);

                    }
                }catch (Exception e){
                    StackTraceElement ste =e.getStackTrace()[0];
                    log.info("请求方式987:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】","支付请求（强在线）", entityXfRecordProcess.getDeviceNo(),entityXfRecordProcess,e,ste.getLineNumber());
                    log.info("请求方式988:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】","支付请求（强在线）", entityXfRecordProcess.getDeviceNo(),retMap,json);
                }
                log.info("请求方式989:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】","支付请求（强在线）", entityXfRecordProcess.getDeviceNo(),retMap,json);
                jsonObject.put("msg",results.get("msg"));
                return 2;
            }
        }catch (Exception e){
            StackTraceElement ste =e.getStackTrace()[0];
            log.info("请求方式90:【{}】,机器号:【{}】,入库新增等待表的数据11:【{}】,异常的返回:【{}】,行号:【{}】","支付请求（强在线）",request.getMachNo(), entityXfRecordProcess,e,ste.getLineNumber());
            log.info("请求方式91:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】","支付请求（强在线）",request.getMachNo(),request,ResultUtil.error(ResultEnum.Err_802));
            //订单号重复
            return -11;
        }
    }


    public int withholding(EntityXfRecordProcess entityXfRecordProcess, QrCardPayRequest request,
                           EntityCardInfo entityCardInfo, JSONObject jsonObject){
        return withholding( entityXfRecordProcess,  request, entityCardInfo,  jsonObject,1);
    }

    @Override
    public void waitPayRefund(EntityXfRecordProcess entityXfRecordProcess) {
        try {
            //更新补缴单为补缴成功
            xfRecordWaitpayService.updateXfRecordWaitpay(entityXfRecordProcess.getComId(),
                    "LX"+entityXfRecordProcess.getOrigOrderNo(),
                    entityXfRecordProcess.getPayTime());

            List<EntityXfRecordProcess> entityXfRecordProcessList = xfRecordProcessService.getWaitPayList(entityXfRecordProcess.getComId(),
                    entityXfRecordProcess.getDeviceNo(),
                    entityXfRecordProcess.getOrigOrderNo());
            if (entityXfRecordProcessList.size() > 1) {
                //判断是否有补缴单和代扣单
                String bjOrderNo = "";
                String dkOrderNo = "";
                String lxOrderNo = "";
                if (entityXfRecordProcess.getOrderNo().startsWith("BJ"))
                    bjOrderNo = entityXfRecordProcess.getOrderNo();
                if (entityXfRecordProcess.getOrderNo().startsWith("DK"))
                    dkOrderNo = entityXfRecordProcess.getOrderNo();
                if (entityXfRecordProcess.getOrderNo().startsWith("LX"))
                    lxOrderNo = entityXfRecordProcess.getOrderNo();
                for (EntityXfRecordProcess entityXfRecordProcess1 : entityXfRecordProcessList) {
                    if (CommonUtil.isNull(bjOrderNo) && entityXfRecordProcess1.getOrderNo().startsWith("BJ")) {
                        bjOrderNo = entityXfRecordProcess1.getOrderNo();
                    }
                    if (CommonUtil.isNull(dkOrderNo) && entityXfRecordProcess1.getOrderNo().startsWith("DK")) {
                        dkOrderNo = entityXfRecordProcess1.getOrderNo();
                    }
                    if (CommonUtil.isNull(lxOrderNo) && entityXfRecordProcess1.getOrderNo().startsWith("LX")) {
                        lxOrderNo = entityXfRecordProcess1.getOrderNo();
                    }
                }
                //退款
                for (EntityXfRecordProcess entityXfRecordProcess1 : entityXfRecordProcessList) {

                    QrCodeRefundRequest request = new QrCodeRefundRequest();
                    request.setMachNo(entityXfRecordProcess1.getDeviceNo());
                    request.setCompanyId(entityXfRecordProcess1.getComId());
                    request.setTradeNo(entityXfRecordProcess1.getDeviceNo() + DateUtils.dateTimeNow() + RandomUtil.generateNumber(6));
                    request.setOrigTradeNo(entityXfRecordProcess1.getOrderNo());
                    Integer refundAmount = entityXfRecordProcess1.getRealMoney().intValue();
                    request.setRefundAmount(Math.abs(refundAmount));

                    //有补缴单  非补缴单全退
                    if (!CommonUtil.isNull(bjOrderNo) && !entityXfRecordProcess1.getOrderNo().equals(bjOrderNo)) {
                        Result result = qrCodeRefund(request);
                        log.info("【补缴订单退款返回】【{}】【{}】【{}】", entityXfRecordProcess1.getDeviceNo(), entityXfRecordProcess1.getOrderNo(), result);
                    }
                    //有补缴单  非补缴单全退
                    if (CommonUtil.isNull(bjOrderNo) &&
                            !CommonUtil.isNull(dkOrderNo) &&
                            !entityXfRecordProcess1.getOrderNo().equals(dkOrderNo)) {
                        Result result = qrCodeRefund(request);
                        log.info("【补缴订单退款返回】【{}】【{}】【{}】", entityXfRecordProcess1.getDeviceNo(), entityXfRecordProcess1.getOrderNo(), result);
                    }
                    //有补缴单  非补缴单全退
                    if (CommonUtil.isNull(bjOrderNo) &&
                            CommonUtil.isNull(dkOrderNo) &&
                            !CommonUtil.isNull(lxOrderNo) &&
                            !entityXfRecordProcess1.getOrderNo().equals(lxOrderNo)) {
                        Result result = qrCodeRefund(request);
                        log.info("【补缴订单退款返回】【{}】【{}】【{}】", entityXfRecordProcess1.getDeviceNo(), entityXfRecordProcess1.getOrderNo(), result);
                    }
                }
            }
        } catch (Exception e) {
            log.info("请求方式:【{}】,机器号:【{}】,异常的返回:【{}】", "定时任务处理补缴订单", entityXfRecordProcess.getDeviceNo(), e);
        }
    }

    @Override
    public Result qrCodeRefund(QrCodeRefundRequest request) {
        try {
            //查询订单号是否存在
            EntityXfRecordProcess entityXfRecordProcess = xfRecordProcessService.selectTradeNo(request.getCompanyId(), request.getOrigTradeNo(), request.getMachNo());
            if (entityXfRecordProcess == null) {
                //原订单号不存在
                return ResultUtil.error(ResultEnum.Err_3036);
            }
            if (entityXfRecordProcess.getConsState() != 1 && entityXfRecordProcess.getConsState() != 3 &&
            entityXfRecordProcess.getConsState() != 5){
                //原订单号不存在
                return ResultUtil.error(ResultEnum.Err_3036);
            }
            //实付全额退款
            Integer absRealMoney = Integer.valueOf(Math.abs(entityXfRecordProcess.getRealMoney().intValue()));
            if (!absRealMoney.equals(request.getRefundAmount())) {
                request.setRefundAmount(absRealMoney);
            }
            Integer consState = entityXfRecordProcess.getConsState();
            request.setOrigTradeNo(entityXfRecordProcess.getOrderNo());
            if (entityXfRecordProcess.getIfRefund() > 0) {
                //
                return ResultUtil.error(ResultEnum.Err_3038);
            }
            Long totalAmount = entityXfRecordProcess.getRealMoney();
            Long id = entityXfRecordProcess.getId();
            Long ifRefund = entityXfRecordProcess.getIfRefund();
            String monthValue = entityXfRecordProcess.getMonthValue();

            String tradeNoRedis = "refund:" + request.getCompanyId() + ":" + request.getMachNo() + ":" + request.getTradeNo();
            if (!redisUtil.lock(tradeNoRedis, 60 * 60)) {
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
            }
            //可退款
            List<Integer> canRefund = new ArrayList<>();
            canRefund.add(1);
            canRefund.add(3);
            canRefund.add(5);
            if (entityXfRecordProcess.getPayState() != 1 || !canRefund.contains(entityXfRecordProcess.getConsState())) {
                return ResultUtil.error(ResultEnum.Err_3037);
            }
            EntityXfRecordProcess refundXfRecordProcess = xfRecordProcessService.selectTradeNo(request.getCompanyId(), request.getTradeNo(), request.getMachNo());


            if (refundXfRecordProcess != null) {
                if (!refundXfRecordProcess.getOrigOrderNo().equals(request.getOrigTradeNo())) {
                    //订单号重复
                    return ResultUtil.error(ResultEnum.Err_802);
                }
                if (entityXfRecordProcess.getIfRefund() > 0) {
                    //退款成功
                    Map<String, Object> map = new HashMap<>();
                    map.put("refundAmount", request.getRefundAmount());
                    return ResultUtil.success(map);
                }
                if (refundXfRecordProcess.getPayState() == 1) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("refundAmount", request.getRefundAmount());
                    return ResultUtil.success(map);
                }
            }

            entityXfRecordProcess.setId(null);
            Date date = new Date();
            entityXfRecordProcess.setCreateTime(date);
            entityXfRecordProcess.setConsTime(date);
            if (Math.abs(entityXfRecordProcess.getRealMoney()) < request.getRefundAmount()) {
                //退款金额超过原订单支付金额
                return ResultUtil.error(ResultEnum.Err_3038);
            }
            entityXfRecordProcess.setConsMoney(-1 * entityXfRecordProcess.getConsMoney());
//            entityXfRecordProcess.setDiscount(0l);
            entityXfRecordProcess.setRealMoney(Long.valueOf(request.getRefundAmount()));
            entityXfRecordProcess.setConsState(2);
            entityXfRecordProcess.setOrigOrderNo(request.getOrigTradeNo());
            entityXfRecordProcess.setOrderNo(request.getTradeNo());
            entityXfRecordProcess.setPayState(0);
            entityXfRecordProcess.setOrderNo(request.getTradeNo());
            entityXfRecordProcess.setIfRefund(0l);
            entityXfRecordProcess.setMonthValue(DateUtils.getStrDate(date, "yyyyMM"));
            entityXfRecordProcess.setPayAmount(-Long.valueOf(request.getRefundAmount()));
            entityXfRecordProcess.setDiscount(-1 * entityXfRecordProcess.getDiscount());
            try {
                int i = xfRecordProcessService.insertEntityXfRecord(request.getCompanyId(), entityXfRecordProcess);
                if (i <= 0) {
                    log.info("请求方式30:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "付款码退款", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
                    //订单号重复
                    return ResultUtil.error(ResultEnum.Err_802);
                }
            } catch (Exception e) {
                StackTraceElement ste = e.getStackTrace()[0];
                log.info("请求方式31:【{}】,机器号:【{}】,入库新增等待表的数据2:【{}】,异常的返回:【{}】,行号:【{}】", "付款码退款", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
                log.info("请求方式32:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "付款码退款", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
            }


            //判断是走什么通道的
            //修改等待表的退款数据
            EntityXfRecordProcess updateXfRecordProces = new EntityXfRecordProcess();
            if (entityXfRecordProcess.getOpType() == 2 || entityXfRecordProcess.getOpTypeDiff() >= 200) {
                //查询配置信息向统一平台发起支付
                EntiyXfMerchPayInfo entiyXfMerchPayInfo = payHandleFunService.configure(entityXfRecordProcess);

                if (entiyXfMerchPayInfo == null) {
                    //商户支付渠道未配置"
                    return ResultUtil.error(ResultEnum.Err_3048);
                }
                Map<String, Object> retMap = new HashMap<>();
                retMap.put("company_id", entiyXfMerchPayInfo.getCompanyId());
                retMap.put("user_name", entiyXfMerchPayInfo.getUserName());
                retMap.put("password", entiyXfMerchPayInfo.getPassword());
                retMap.put("out_trade_no", request.getOrigTradeNo());
                retMap.put("out_refund_no", request.getTradeNo());
                retMap.put("pos_no", request.getMachNo());
                retMap.put("total_amount", Math.abs(totalAmount));
                retMap.put("refund_fee", request.getRefundAmount());
                retMap.put("refund_desc", "退款");
                //向统一支付平台发起支付
                String json = "";
                String payUrl = companyInfoService.getPayCenterUrl(request.getCompanyId(), entiyXfMerchPayInfo.getCompanyId());
                if (entityXfRecordProcess.getPayWay() == 28 || entityXfRecordProcess.getOpTypeDiff() == 316l) {
                    json = HttpUtils.postsJson(payUrl + "/withholding/refund.do", retMap);
                } else {
                    json = HttpUtils.postsJson(payUrl + "/unifiedmicropay/refund.do", retMap);
                }
                JSONObject results = JSON.parseObject(json);
                if (results.getInteger("code") != 200) {
                    log.info("请求方式33:【{}】,机器号:【{}】,入库新增的数据:【{}】,返回:【{}】", "付款码退款", request.getMachNo(), entityXfRecordProcess, "付款码退款失败");
                    log.info("请求方式34:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "付款码退款", request.getMachNo(), retMap, json);
                    return ResultUtil.error(ResultEnum.Err_3039);
                }
                Map<String, String> dataMap = (Map<String, String>) JSON.parse(results.getString("data"));
                updateXfRecordProces.setPayChannelNo(entiyXfMerchPayInfo.getCompanyId());

                entityXfRecordProcess.setChannelOrderNo(dataMap.get("refund_id"));
                entityXfRecordProcess.setPayAmount(-Long.valueOf(dataMap.get("refund_fee")));

                updateXfRecordProces.setChannelOrderNo(dataMap.get("refund_id"));
                updateXfRecordProces.setPayAmount(-Long.valueOf(dataMap.get("refund_fee")));
            } else if (//entiyEntiyXfRecordProcess.getOpType()==1 &&
                    entityXfRecordProcess.getOpTypeDiff() == 100) {
                //虚拟账户只允许退一次款，不然对于两个钱包都扣款的交易记录不好退款
                if (ifRefund > 0) {
                    return ResultUtil.error(ResultEnum.Err_3038);
                }
                EntityCardInfo entityCardInfo = xfCardInfoService.selectCard(request.getCompanyId(), entityXfRecordProcess.getCardNo());
                if (entityXfRecordProcess.getOpType() == 22 || entityXfRecordProcess.getOpType() == 21 || entityXfRecordProcess.getOpType() == 25) {
                    entityCardInfo = xfCardInfoService.selectCardByPid(request.getCompanyId(), entityXfRecordProcess.getPId());
                }
//				EntityXfAccountInfo entityXfAccountInfo=xfAccountInfoService.selectAccount(request.getCompanyId(),entityCardInfo.getAccountNo());
                EntityXfAccountInfo entityXfAccountInfo = xfAccountInfoService.selectAccountPid(request.getCompanyId(), entityXfRecordProcess.getPId());
                Long refundAmount = Long.valueOf(Math.abs(request.getRefundAmount()));
                Long chargeBalance = refundAmount + entityXfAccountInfo.getAccountRechargeMoney();
                Long subBalance = Long.valueOf(Math.abs(entityXfRecordProcess.getSubMoney()));
                entityXfRecordProcess.setChargeBalance(chargeBalance);
                updateXfRecordProces.setChargeBalance(chargeBalance);
                if (entityCardInfo != null) {
                    xfCardInfoService.upateCardMoneyA(request.getCompanyId(), entityCardInfo);
                }
                //修改等待表的原订单表的数据
                EntityXfRecordProcess updateXfRecordProcess = new EntityXfRecordProcess();
                updateXfRecordProcess.setId(id);
                updateXfRecordProcess.setRefundTime(new Date());
                updateXfRecordProcess.setIfRefund(ifRefund + 1);

                entityXfRecordProcess.setChargeMoney(Math.abs(entityXfRecordProcess.getChargeMoney()));
                updateXfRecordProces.setChargeMoney(Math.abs(entityXfRecordProcess.getChargeMoney()));
                entityXfRecordProcess.setSubMoney(subBalance);
                updateXfRecordProces.setSubMoney(subBalance);
                updateXfRecordProces.setId(entityXfRecordProcess.getId());
                updateXfRecordProces.setPayTime(new Date());
                updateXfRecordProces.setPayState(1);


                boolean updateAccount = xfAccountInfoService.updateAccountMoneyTransactional(request.getCompanyId(), Math.abs(entityXfRecordProcess.getChargeMoney()), subBalance, entityXfAccountInfo.getId(),updateXfRecordProcess, updateXfRecordProces);
                if (!updateAccount) {
                    return ResultUtil.error(ResultEnum.Err_3039);
                }

                if (consState == 3 || consState == 5) {
                    xfGoodsListProcessService.xfGoodsListRrfund(entityXfRecordProcess.getComId(), entityXfRecordProcess.getOrigOrderNo());
                }
                //修改成功表的原订单表的数据
                updateXfRecordProcess.setComId(request.getCompanyId());
                updateXfRecordProcess.setOrderNo(request.getOrigTradeNo());
                updateXfRecordProcess.setMonthValue(monthValue);
                updateXfRecordProcess.setDeviceNo(request.getMachNo());
                EntityXfRecord entityXfRecord = JSON.parseObject(JSON.toJSONString(updateXfRecordProcess), EntityXfRecord.class);
                Result result = xfRecordFeign.updateXfRecord(entityXfRecord);
                if (result.getCode() != 200) {
                    log.info("请求方式37:【{}】,机器号:【{}】,修改成功表的数据:【{}】,返回:【{}】", "付款码退款", request.getMachNo(), entityXfRecordProcess, "修改原订单信息失败");
                }
                if (consState == 3 || consState == 5) {
                    RefundOrderDishesRequest refundOrderDishesRequest = new RefundOrderDishesRequest();
                    refundOrderDishesRequest.setComId(entityXfRecordProcess.getComId());
                    refundOrderDishesRequest.setOrderNo(request.getOrigTradeNo());
                    refundOrderDishesRequest.setMonthValue(entityXfRecordProcess.getMonthValue());
                    refundOrderDishesRequest.setRemark("菜品退款");
                    xfRecordFeign.refund(refundOrderDishesRequest);
                }
                //新增成功表的退款数据
                Date payTime = new Date();
                entityXfRecordProcess.setPayTime(payTime);
                entityXfRecordProcess.setPayState(1);

                try {
                    MqSaveOrderVo mqSaveOrderVo = new MqSaveOrderVo();
                    mqSaveOrderVo.setComId(request.getCompanyId());
                    mqSaveOrderVo.setId(entityXfRecordProcess.getId());
                    mqSaveOrderVo.setMachNo(entityXfRecordProcess.getDeviceNo());
                    saveOrderProductService.saveOrder(JSON.toJSONString(mqSaveOrderVo));
                } catch (Exception e) {
                    StackTraceElement ste = e.getStackTrace()[0];
                    log.info("请求方式1006:【{}】,机器号:【{}】,扫码退款-插成功库:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（退款）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, e, ste.getLineNumber());
                }


                Map<String, Object> map = new HashMap<>();
                map.put("refundAmount", request.getRefundAmount());
                return ResultUtil.success(map);
            }

            //修改等待表的原订单表的数据
            EntityXfRecordProcess updateXfRecordProcess = new EntityXfRecordProcess();
            updateXfRecordProcess.setId(id);

            updateXfRecordProcess.setRefundTime(new Date());
            updateXfRecordProcess.setIfRefund(ifRefund + 1);
            try {
                int i = xfRecordProcessService.updateEntityXfRecord(request.getCompanyId(), updateXfRecordProcess);
                if (i <= 0) {
                    log.info("请求方式35:【{}】,机器号:【{}】,入库修改的数据:【{}】,返回:【{}】", "付款码退款", request.getMachNo(), updateXfRecordProcess, "付款码退款失败");
                }
            } catch (Exception e) {
                StackTraceElement ste = e.getStackTrace()[0];
                log.info("请求方式36:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】", "付款码退款", request.getMachNo(), updateXfRecordProcess, e, ste.getLineNumber());
            }
            if (consState == 3 || consState == 5) {
                xfGoodsListProcessService.xfGoodsListRrfund(entityXfRecordProcess.getComId(), entityXfRecordProcess.getOrigOrderNo());
            }
            //修改成功表的原订单表的数据
            updateXfRecordProcess.setComId(request.getCompanyId());
            updateXfRecordProcess.setOrderNo(request.getOrigTradeNo());
            updateXfRecordProcess.setMonthValue(monthValue);
            updateXfRecordProcess.setDeviceNo(request.getMachNo());
            EntityXfRecord entityXfRecord = JSON.parseObject(JSON.toJSONString(updateXfRecordProcess), EntityXfRecord.class);
            Result result = xfRecordFeign.updateXfRecord(entityXfRecord);
            if (result.getCode() != 200) {
                log.info("请求方式37:【{}】,机器号:【{}】,修改成功表的数据:【{}】,返回:【{}】", "付款码退款", request.getMachNo(), entityXfRecordProcess, "修改原订单信息失败");
            }
            if (consState == 3 || consState == 5) {
                RefundOrderDishesRequest refundOrderDishesRequest = new RefundOrderDishesRequest();
                refundOrderDishesRequest.setComId(entityXfRecordProcess.getComId());
                refundOrderDishesRequest.setOrderNo(request.getOrigTradeNo());
                refundOrderDishesRequest.setMonthValue(entityXfRecordProcess.getMonthValue());
                refundOrderDishesRequest.setRemark("菜品退款");
                xfRecordFeign.refund(refundOrderDishesRequest);
            }
            //新增成功表的退款数据
            Date payTime = new Date();
            entityXfRecordProcess.setPayTime(payTime);
            entityXfRecordProcess.setPayState(1);

//            Result sveResult = xfRecordFeign.sveXfRecord(entityXfRecordProcess);
//            if (sveResult.getCode() != 200) {
//                log.info("请求方式38:【{}】,机器号:【{}】,入库成功的数据:【{}】,返回:【{}】", "付款码退款", request.getMachNo(), updateXfRecordProcess, "添加入库失败");
//            }
            try {
                MqSaveOrderVo mqSaveOrderVo = new MqSaveOrderVo();
                mqSaveOrderVo.setComId(request.getCompanyId());
                mqSaveOrderVo.setId(entityXfRecordProcess.getId());
                mqSaveOrderVo.setMachNo(entityXfRecordProcess.getDeviceNo());
                saveOrderProductService.saveOrder(JSON.toJSONString(mqSaveOrderVo));
            } catch (Exception e) {
                StackTraceElement ste = e.getStackTrace()[0];
                log.info("请求方式1006:【{}】,机器号:【{}】,扫码退款-插成功库:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（退款）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, e, ste.getLineNumber());
            }

            updateXfRecordProces.setId(entityXfRecordProcess.getId());
            updateXfRecordProces.setPayTime(payTime);
            updateXfRecordProces.setPayState(1);

            try {
                int i = xfRecordProcessService.updateEntityXfRecord(request.getCompanyId(), updateXfRecordProces);
                if (i <= 0) {
                    log.info("请求方式39:【{}】,机器号:【{}】,等待表的入库修改的数据:【{}】,返回:【{}】", "付款码退款", request.getMachNo(), updateXfRecordProcess, "等待表修改入库失败");
                }
            } catch (Exception e) {
                StackTraceElement ste = e.getStackTrace()[0];
                log.info("请求方式40:【{}】,机器号:【{}】,等待表的入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】", "付款码退款", request.getMachNo(), updateXfRecordProcess, e, ste.getLineNumber());
            }
            Map<String, Object> map = new HashMap<>();
            map.put("refundAmount", request.getRefundAmount());
            return ResultUtil.success(map);
        } catch (Exception e) {
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式41:【{}】,机器号:【{}】,请求参数:【{}】,异常:【{}】,行号:【{}】", "退款异常", request.getMachNo(), request, e, ste.getLineNumber());
            return ResultUtil.error(ResultEnum.Err_3031);
        }
    }


    /**
     * @return int
     * @author lu
     * @date 2021/5/26 15:38
     * @param:
     * @description 判断用什么码支付
     */
    private int payCode(String strCode) {
        if (strCode.equals("weixin")) {
            return 201;
        } else if (strCode.equals("alipay")) {
            return 202;
        } else if (strCode.equals("unionpay")) {
            return 203;
        } else if (strCode.equals("E-CNY")) {
            return 204;
        } else if (strCode.equals("ccbb")) {
            return 206;
        } else if (strCode.equals("icbc")) {
            return 207;
        } else if (strCode.equals("shebao")) {
            return 208;
        }
        return 0;
    }

    /**
     * 代扣子商户获取代扣顶级签约号
     * @return 递归商户号
     */
    private Long getUsefulMerchId(Long comId,Long merchId){
        if(merchId==0 || merchId==null){
            return  0l;
        }
        EntityXfMerchantInfo entityXfMerchantInfo = xfMerchantInfoService.selectParentMerchId(comId,merchId.intValue());
        if(entityXfMerchantInfo==null ){
            return  0l;
        }
        //如果是代扣 子商户
        if(entityXfMerchantInfo.getWithholdSubmerch()){
            if(entityXfMerchantInfo.getParentMerchId()==null){
                return  0l;
            }
            return getUsefulMerchId(comId,entityXfMerchantInfo.getParentMerchId().longValue());
        }else{
            return merchId;
        }
    }


    //0未处理  1返回成功 2返回失败 >0上一层直接返回
    private int waitPayOnline(EntityXfRecordProcess entityXfRecordProcess, QrCardPayRequest request,EntityXfRecordProcess updateXfRecordProcess) {
        try {
            if (entityXfRecordProcess.getOrderNo().startsWith("DK")) {
                boolean bj = payHandleFunService.checkIfWaitPay(entityXfRecordProcess.getComId(), entityXfRecordProcess.getMealNo(),entityXfRecordProcess.getMerchId());
                if (bj) {
                    EntityXfRecordWaitpay entityXfRecordWaitpay = JSON.parseObject(JSON.toJSONString(entityXfRecordProcess), EntityXfRecordWaitpay.class);
                    entityXfRecordWaitpay.setOrderNo("LX" + request.getTradeNo());
                    entityXfRecordWaitpay.setPlatOrderNo("DK" + request.getTradeNo());
                    entityXfRecordWaitpay.setOrigOrderNo(request.getTradeNo());
                    entityXfRecordWaitpay.setPayState(-1);
                    updateXfRecordProcess.setOrigOrderNo(request.getTradeNo());
                    updateXfRecordProcess.setPlatOrderNo("LX" + request.getTradeNo());
                    boolean sacx = xfRecordWaitpayService.saveXfRecordWaitpay2(entityXfRecordProcess.getComId(), entityXfRecordWaitpay, updateXfRecordProcess);

                    try {
                        //判断是否有补缴
                        EntityXfRepairpayConfig entityXfRepairpayConfig = xfRepairpayConfigService.getByComId(entityXfRecordProcess.getComId(),entityXfRecordProcess.getMerchId());;

                        EntityXfRecordWaitpay entityXfRecordWaitpay1 = xfRecordWaitpayService.getRepairPaySum(entityXfRecordProcess.getComId(), entityXfRecordProcess.getPId());
                        if (entityXfRepairpayConfig.getAllowMoney() != null
                                && entityXfRepairpayConfig.getAllowMoney() > 0) {
                            if (entityXfRecordWaitpay1 != null && entityXfRecordWaitpay1.getAmount().compareTo(entityXfRepairpayConfig.getAllowMoney()) >= 0) {

                                EntityXfAccountInfo entityXfAccountInfo = xfAccountInfoService.selectAccountPid(request.getCompanyId(), entityXfRecordProcess.getPId());

                                EntityXfAccountInfo entityXfAccountInfo2 = new EntityXfAccountInfo();
                                entityXfAccountInfo2.setId(entityXfAccountInfo.getId());
                                entityXfAccountInfo2.setComId(request.getCompanyId());
                                entityXfAccountInfo2.setPId(entityXfRecordProcess.getPId());
                                entityXfAccountInfo2.setAccountState(1);
                                payConfigClientService.UpdateXFAccount(entityXfAccountInfo2);
                            }
                        }

                    } catch (Exception e) {
                        log.info("请求方式2246:【{}】,机器号:【{}】,补缴金额统计:【{}】,异常的返回:【{}】", "支付请求（强在线补缴）", entityXfRecordProcess.getDeviceNo(), updateXfRecordProcess, e);
                    }


                    if (sacx) {
                        return 1;
                    } else {
                        return 2;
                    }
                }
            }
        } catch (Exception e) {
            log.info("请求方式224:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】", "支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), updateXfRecordProcess, e);
        }
        return 0;
    }


    @Override
    public Result gzhRefund(GzhRechageRefundRequest request) {
        try {
            //查询订单号是否存在
            EntityXfRecordProcess entityXfRecordProcess = xfRecordProcessService.selectTradeNo(request.getComId(), request.getOrigTradeNo(), request.getMachNo());
            if (entityXfRecordProcess == null) {
                //原订单号不存在
                return ResultUtil.error(ResultEnum.Err_3036);
            }
            if (entityXfRecordProcess.getConsState() != 10 ){
                //原订单号不存在
                return ResultUtil.error(ResultEnum.Err_3204);
            }

            if (entityXfRecordProcess.getSubAccount() > 0 || entityXfRecordProcess.getOpTypeDiff()<200){
                //暂不支持
                return ResultUtil.error(ResultEnum.Err_3205);
            }

            if (entityXfRecordProcess.getIfRefund() > 0) {
                //已退款
                return ResultUtil.error(ResultEnum.Err_3038);
            }

            Long ifRefund = entityXfRecordProcess.getIfRefund();
            Long id = entityXfRecordProcess.getId();
            String monthValue = entityXfRecordProcess.getMonthValue();

            String tradeNoRedis = "refund:" + request.getComId() + ":" + request.getMachNo() + ":" + request.getTradeNo();
            if (!redisUtil.lock(tradeNoRedis, 3 * 60)) {
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
            }

            if (entityXfRecordProcess.getPayState() != 1 ) {
                return ResultUtil.error(ResultEnum.Err_3037);
            }
            EntityXfRecordProcess refundXfRecordProcess = xfRecordProcessService.selectTradeNo(request.getComId(), request.getTradeNo(), request.getMachNo());

            if (refundXfRecordProcess != null) {
                if (!refundXfRecordProcess.getOrigOrderNo().equals(request.getOrigTradeNo())) {
                    //订单号重复
                    return ResultUtil.error(ResultEnum.Err_802);
                }
                if (entityXfRecordProcess.getIfRefund() > 0) {
                    //退款成功
                    Map<String, Object> map = new HashMap<>();
                    map.put("refundAmount", entityXfRecordProcess.getChargeMoney());
                    return ResultUtil.success(map);
                }
                if (refundXfRecordProcess.getPayState() == 1) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("refundAmount", entityXfRecordProcess.getChargeMoney());
                    return ResultUtil.success(map);
                }
            }


            EntityXfAccountInfo entityXfAccountInfo = xfAccountInfoService.selectAccountPid(request.getComId(), entityXfRecordProcess.getPId());
            if (entityXfAccountInfo==null || entityXfAccountInfo.getAccountState()!=0) {
                //账号异常
                return ResultUtil.error(ResultEnum.Err_3105);
            }

            if(entityXfAccountInfo.getAccountRechargeMoney().compareTo(Math.abs(request.getRefundMoney().longValue()))<0){
                return ResultUtil.error(ResultEnum.Err_3201);
            }

            if(entityXfRecordProcess.getRealMoney().compareTo(request.getRefundMoney().longValue())<0){
                return ResultUtil.error(ResultEnum.Err_3201);
            }

            if(entityXfRecordProcess.getChargeMoney().compareTo(request.getRefundMoney().longValue())<0){
                return ResultUtil.error(ResultEnum.Err_3201);
            }

            entityXfRecordProcess.setId(null);
            Date date = new Date();
            entityXfRecordProcess.setCreateTime(date);
            entityXfRecordProcess.setConsTime(date);

            entityXfRecordProcess.setConsMoney(-1 * request.getRefundMoney().longValue());
            entityXfRecordProcess.setRealMoney(-1 * request.getRefundMoney().longValue());
            entityXfRecordProcess.setPayAmount(-1 * request.getRefundMoney().longValue());
            entityXfRecordProcess.setChargeMoney(-1 * request.getRefundMoney().longValue());
            entityXfRecordProcess.setSubMoney(-1 * entityXfRecordProcess.getSubMoney());
            entityXfRecordProcess.setConsState(11);
            entityXfRecordProcess.setOrigOrderNo(request.getOrigTradeNo());
            entityXfRecordProcess.setOrderNo(request.getTradeNo());
            entityXfRecordProcess.setPayState(5);
            entityXfRecordProcess.setIfRefund(0l);
            entityXfRecordProcess.setPayTime(null);
            entityXfRecordProcess.setMonthValue(DateUtils.getStrDate(date, "yyyyMM"));

            if (entityXfRecordProcess.getSubMoney() != 0 && -1 * entityXfRecordProcess.getSubMoney() > entityXfAccountInfo.getAccountSubsidyMoney()) {
                entityXfRecordProcess.setSubMoney(-1 * entityXfAccountInfo.getAccountSubsidyMoney());
            }

            try {
                EntityXfRecordProcess updateXfRecordProcess = new EntityXfRecordProcess();
                updateXfRecordProcess.setId(id);
                updateXfRecordProcess.setPayState(5);

                xfAccountInfoService.gzhRefundMoney(request.getComId(),entityXfAccountInfo.getId(),entityXfRecordProcess,updateXfRecordProcess);
            } catch (Exception e) {
                StackTraceElement ste = e.getStackTrace()[0];
                log.info("请求方式231:【{}】,机器号:【{}】,入库新增等待表的数据2:【{}】,异常的返回:【{}】,行号:【{}】", "付款码退款", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
                log.info("请求方式232:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "付款码退款", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
            }

            //判断是走什么通道
            //查询配置信息向统一平台发起支付

            EntiyXfMerchPayInfo entiyXfMerchPayInfo = xfMerchPayInfoService.selectConfigure(entityXfRecordProcess.getComId(), entityXfRecordProcess.getPayChannelNo());

            if (entiyXfMerchPayInfo == null) {
                //商户支付渠道未配置"
                return ResultUtil.error(ResultEnum.Err_3048);
            }
            Map<String, Object> retMap = new HashMap<>();
            retMap.put("company_id", entiyXfMerchPayInfo.getCompanyId());
            retMap.put("user_name", entiyXfMerchPayInfo.getUserName());
            retMap.put("password", entiyXfMerchPayInfo.getPassword());
            retMap.put("out_trade_no", request.getOrigTradeNo());
            retMap.put("out_refund_no", request.getTradeNo());
            retMap.put("pos_no", request.getMachNo());
            retMap.put("total_amount", Math.abs(entityXfRecordProcess.getRealMoney()));
            retMap.put("refund_fee", Math.abs(entityXfRecordProcess.getRealMoney()));
            retMap.put("refund_desc", "gzh退款");
            //向统一支付平台发起支付
            String json = "";
            String payUrl = companyInfoService.getPayCenterUrl(request.getComId(), entiyXfMerchPayInfo.getCompanyId());
            if (entityXfRecordProcess.getPayWay() == 28 || entityXfRecordProcess.getOpTypeDiff() == 316l) {
                json = HttpUtils.postsJson(payUrl + "/withholding/refund.do", retMap);
            } else {
                json = HttpUtils.postsJson(payUrl + "/unifiedmicropay/refund.do", retMap);
            }
            JSONObject results = JSON.parseObject(json);
            if (results.getInteger("code") != 200) {
                log.info("请求方式233:【{}】,机器号:【{}】,入库新增的数据:【{}】,返回:【{}】", "公众号退款", request.getMachNo(), entityXfRecordProcess, "付款码退款失败");
                log.info("请求方式234:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "公众号退款", request.getMachNo(), retMap, json);
                if(results.getInteger("code") == 32 || results.getInteger("code") == 6 || results.getInteger("code") == 7 || results.getInteger("code") == 19)   return ResultUtil.error(ResultEnum.Err_3206);
                if(results.getInteger("code") == 300 || results.getInteger("code") == 21){
                    //明确失败的 补回金额
                    try {
                        entityXfRecordProcess.setPayState(2);

                        EntityXfRecordProcess updateXfRecordProcess = new EntityXfRecordProcess();
                        updateXfRecordProcess.setId(id);
                        updateXfRecordProcess.setPayState(1);

                        xfAccountInfoService.gzhRefundOrderStatusFail(request.getComId(), entityXfAccountInfo.getId(),entityXfRecordProcess,updateXfRecordProcess);
                    } catch (Exception e) {
                        StackTraceElement ste = e.getStackTrace()[0];
                        log.info("请求方式236RE:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】", "公众号退款补回", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
                        return ResultUtil.error(ResultEnum.Err_3039);
                    }
                }
                return ResultUtil.error(ResultEnum.Err_3039);
            }
            Map<String, String> dataMap = (Map<String, String>) JSON.parse(results.getString("data"));

            entityXfRecordProcess.setChannelOrderNo(dataMap.get("refund_id"));
            entityXfRecordProcess.setPayAmount(Long.valueOf(dataMap.get("refund_fee")));

            //修改等待表的原订单表的数据
            Date payTime = new Date();
            EntityXfRecordProcess updateXfRecordProcess = new EntityXfRecordProcess();
            updateXfRecordProcess.setId(id);
            updateXfRecordProcess.setRefundTime(payTime);
            updateXfRecordProcess.setIfRefund(ifRefund + 1);

            EntityXfRecordProcess updateXfRecordRefund =  new EntityXfRecordProcess();
            updateXfRecordRefund.setId(entityXfRecordProcess.getId());
            updateXfRecordRefund.setPayTime(payTime);
            updateXfRecordRefund.setPayState(1);
            updateXfRecordRefund.setChargeMoney(entityXfRecordProcess.getChargeMoney());
            updateXfRecordRefund.setSubMoney(entityXfRecordProcess.getSubMoney());
            updateXfRecordRefund.setPayAmount(-1 * entityXfRecordProcess.getPayAmount());
            updateXfRecordRefund.setChannelOrderNo(dataMap.get("refund_id"));
            updateXfRecordRefund.setPayChannelNo(entiyXfMerchPayInfo.getCompanyId());
            if (entityXfRecordProcess.getSubMoney() != 0 && -1 * entityXfRecordProcess.getSubMoney() > entityXfAccountInfo.getAccountSubsidyMoney()) {
                updateXfRecordRefund.setSubMoney(-1 * entityXfAccountInfo.getAccountSubsidyMoney());
            }
            updateXfRecordRefund.setChargeBalance(entityXfAccountInfo.getAccountRechargeMoney() + updateXfRecordRefund.getChargeMoney());
            updateXfRecordRefund.setSubBalance(entityXfAccountInfo.getAccountSubsidyMoney() + updateXfRecordRefund.getSubMoney());

            try {
                xfAccountInfoService.gzhRefundOrderStatusSucc(request.getComId(), updateXfRecordProcess,updateXfRecordRefund);
            } catch (Exception e) {
                StackTraceElement ste = e.getStackTrace()[0];
                log.info("请求方式236:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】", "公众号退款", request.getMachNo(), updateXfRecordProcess, e, ste.getLineNumber());
                return ResultUtil.error(ResultEnum.Err_3039);
            }

            //修改成功表的原订单表的数据
            updateXfRecordProcess.setComId(request.getComId());
            updateXfRecordProcess.setOrderNo(request.getOrigTradeNo());
            updateXfRecordProcess.setMonthValue(monthValue);
            updateXfRecordProcess.setDeviceNo(request.getMachNo());
            EntityXfRecord entityXfRecord = JSON.parseObject(JSON.toJSONString(updateXfRecordProcess), EntityXfRecord.class);
            Result result = xfRecordFeign.updateXfRecord(entityXfRecord);
            if (result.getCode() != 200) {
                log.info("请求方式37:【{}】,机器号:【{}】,修改成功表的数据:【{}】,返回:【{}】", "付款码退款", request.getMachNo(), entityXfRecordProcess, "修改原订单信息失败");
            }

            //新增成功表的退款数据
            try {
                MqSaveOrderVo mqSaveOrderVo = new MqSaveOrderVo();
                mqSaveOrderVo.setComId(request.getComId());
                mqSaveOrderVo.setId(entityXfRecordProcess.getId());
                mqSaveOrderVo.setMachNo(entityXfRecordProcess.getDeviceNo());
                saveOrderProductService.saveOrder(JSON.toJSONString(mqSaveOrderVo));
            } catch (Exception e) {
                StackTraceElement ste = e.getStackTrace()[0];
                log.info("请求方式1006:【{}】,机器号:【{}】,扫码退款-插成功库:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（退款）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, e, ste.getLineNumber());
            }

            Map<String, Object> map = new HashMap<>();
            map.put("refundAmount", Math.abs(entityXfRecordProcess.getRealMoney()));
            return ResultUtil.success(map);
        } catch (Exception e) {
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式41:【{}】,机器号:【{}】,请求参数:【{}】,异常:【{}】,行号:【{}】", "退款异常", request.getMachNo(), request, e, ste.getLineNumber());
            return ResultUtil.error(ResultEnum.Err_3031);
        }
    }

}
